Databases Reference
In-Depth Information
easy as specifying the value that you are looking for. For example, to find all documents
where the value for "age" is 27, we can add that key/value pair to the query document:
> db.users.find({"age" : 27})
If we have a string we want to match, such as a "username" key with the value "joe" ,
we use that key/value pair instead:
> db.users.find({"username" : "joe"})
Multiple conditions can be strung together by adding more key/value pairs to the query
document, which gets interpreted as “condition1 AND condition2 AND … AND
conditionN.” For instance, to get all users who are 27-year-olds with the username
“joe,” we can query for the following:
> db.users.find({"username" : "joe", "age" : 27})
Specifying Which Keys to Return
Sometimes, you do not need all of the key/value pairs in a document returned. If this
is the case, you can pass a second argument to find (or findOne ) specifying the keys you
want. This reduces both the amount of data sent over the wire and the time and memory
used to decode documents on the client side.
For example, if you have a user collection and you are interested only in the "user
name" and "email" keys, you could return just those keys with the following query:
> db.users.find({}, {"username" : 1, "email" : 1})
{
"_id" : ObjectId("4ba0f0dfd22aa494fd523620"),
"username" : "joe",
"email" : "joe@example.com"
}
As you can see from the previous output, the "_id" key is always returned, even if it
isn't specifically listed.
You can also use this second parameter to exclude specific key/value pairs from the
results of a query. For instance, you may have documents with a variety of keys, and
the only thing you know is that you never want to return the "fatal_weakness" key:
> db.users.find({}, {"fatal_weakness" : 0})
This can even prevent "_id" from being returned:
> db.users.find({}, {"username" : 1, "_id" : 0})
{
"username" : "joe",
}
 
Search WWH ::




Custom Search