Database Reference
In-Depth Information
If the user later decides that she no longer wants her country stored in her profile, she
can remove the value just as easily using the $unset operator:
> db.users.update({username: "smith"}, {$unset: {country: 1}})
Let's enrich this example. You're representing your data with documents, which, as
you saw in chapter 1, can contain complex data structures. So let's suppose that, in
addition to storing profile information, your users can also store lists of their favorite
things. A good document representation might look something like this:
{ username: "smith",
favorites: {
cities: ["Chicago", "Cheyenne"],
movies: ["Casablanca", "For a Few Dollars More", "The Sting"]
}
}
The favorites key points to an object containing two other keys which point to lists
of favorite cities and movies. Given what you know already, can you think of a way to
modify the original smith document to look like this? The $set operator should come
to mind. Note in this example that you're practically rewriting the document and that
this is a perfectly acceptable use of $set :
> db.users.update( {username: "smith"},
{ $set: {favorites:
{
cities: ["Chicago", "Cheyenne"],
movies: ["Casablanca", "The Sting"]
}
}
})
Let's modify jones similarly, but in this case you'll add a couple of favorite movies:
db.users.update( {username: "jones"},
{"$set": {favorites:
{
movies: ["Casablanca", "Rocky"]
}
}
})
Now query the users collection to make sure that both updates succeeded:
> db.users.find()
With a couple of example documents at your fingertips, you can now begin to see the
power of MongoDB's query language. In particular, the query engine's ability to reach
into nested inner objects and match against array elements proves useful in this situa-
tion. You can accomplish this kind query using a special dot notation. Suppose that
you want to find all users who like the movie Casablanca . Such a query looks like this:
> db.users.find({"favorites.movies": "Casablanca"})
Search WWH ::




Custom Search