Database Reference
In-Depth Information
The dot between favorites and movies instructs the query engine to look for a key
named favorites that points to an object with an inner key named movies and then
to match the value of the inner key. Thus this query returns both user documents. To
take a more involved example, suppose you know, a priori, that any user who likes Cas-
ablanca also like The Maltese Falcon and that you want to update your database to reflect
this fact. How would you represent this as a MongoDB update?
You could conceivably use the $set operator again, but that would require you to
rewrite and send the entire array of movies. Since all you want to do is add an element
to the list, you're better off using either $push or $addToSet . Both operators add an
item to an array, but the second does so uniquely, preventing a duplicate addition.
This is the update you're looking for:
db.users.update( {"favorites.movies": "Casablanca"},
{$addToSet: {"favorites.movies": "The Maltese Falcon"} },
false,
true )
Most of this should be decipherable. The first argument, a query selector, matches
against users who have Casablanca in their movies list. The second argument adds The
Maltese Falcon to that list using the $addToSet operator. The third argument, false ,
can be ignored for now. The fourth argument, true , indicates that this is a multi-
update. By default, a MongoDB update operation will apply only to the first document
matched by the query selector. If you want the operation to apply to all documents
matched, then you must be explicit about that. Because you want your update to apply
to both smith and jones , the multi-update is necessary.
We ' ll co ve r u p d a t e s i n m o re d e t a i l l a t e r, b u t do tr y these e xamples befo re mo ving on.
2.1.4
Deleting data
You now know the basics of creating, reading, and updating data through the
MongoDB shell. We've saved the simplest operation, removing data, for last.
If given no parameters, a remove operation will clear a collection of all its docu-
ments. To get rid of, say, a foo collection, you enter
> db.foo.remove()
You often need to remove only a certain subset of a collection's documents, and for
that, you can pass a query selector to the remove() method. If you want to remove all
users whose favorite city is Cheyenne, the expression is pretty straightforward:
> db.users.remove({"favorites.cities": "Cheyenne"})
Note that the remove() operation doesn't actually delete the collection; it merely
removes documents from a collection. You can think of it as being analogous to SQL 's
DELETE and TRUNCATE TABLE directives.
If your intent is to delete the collection along with all of its indexes, use the drop()
method:
> db.users.drop()
Search WWH ::




Custom Search