Databases Reference
In-Depth Information
"age" : 45
}
we can query for someone named Joe Schmoe with the following:
> db.people.find({"name" : {"first" : "Joe", "last" : "Schmoe"}})
However, if Joe decides to add a middle name key, suddenly this query won't work
anymore; it doesn't match the entire embedded document! This type of query is also
order-sensitive; {"last" : "Schmoe", "first" : "Joe"} would not be a match.
If possible, it's usually a good idea to query for just a specific key or keys of an embedded
document. Then, if your schema changes, all of your queries won't suddenly break
because they're no longer exact matches. You can query for embedded keys using dot-
notation:
> db.people.find({"name.first" : "Joe", "name.last" : "Schmoe"})
Now, if Joe adds more keys, this query will still match his first and last names.
This dot-notation is the main difference between query documents and other document
types. Query documents can contain dots, which mean “reach into an embedded
document.” Dot-notation is also the reason that documents to be inserted cannot con-
tain the . character. Oftentimes people run into this limitation when trying to save URLs
as keys. One way to get around it is to always perform a global replace before inserting
or after retrieving, substituting a character that isn't legal in URLs for the dot (.)
character.
Embedded document matches can get a little tricky as the document structure gets
more complicated. For example, suppose we are storing blog posts and we want to find
comments by Joe that were scored at least a five. We could model the post as follows:
> db.blog.find()
{
"content" : "...",
"comments" : [
{
"author" : "joe",
"score" : 3,
"comment" : "nice post"
},
{
"author" : "mary",
"score" : 6,
"comment" : "terrible post"
}
]
}
Now, we can't query using db.blog.find({"comments" : {"author" : "joe", "score" :
{"$gte" : 5}}}) . Embedded document matches have to match the whole document,
and this doesn't match the "comment" key. It also wouldn't work to do
db.blog.find({"comments.author" : "joe", "comments.score" : {"$gte" : 5}}) ,
 
Search WWH ::




Custom Search