Database Reference
In-Depth Information
and their behavior is as expected. But beginners sometimes struggle with combining
these operators. A common mistake is to repeat the search key:
db.users.find({age: {$gte: 0}, age: {$lte: 30})
Because keys can't be at the same level in the same document, this query selector is
invalid, and will apply only one of the two range operators. You can properly express
this query as follows:
db.users.find({age: {$gte: 0, $lte: 30})
The only other surprise regarding the range operators involves types. Range queries
will match values only if they have the same type as the value to be compared against. 5
For example, suppose you have a collection with the following documents:
{ "_id" : ObjectId("4caf82011b0978483ea29ada"), "value" : 97 }
{ "_id" : ObjectId("4caf82031b0978483ea29adb"), "value" : 98 }
{ "_id" : ObjectId("4caf82051b0978483ea29adc"), "value" : 99 }
{ "_id" : ObjectId("4caf820d1b0978483ea29ade"), "value" : "a" }
{ "_id" : ObjectId("4caf820f1b0978483ea29adf"), "value" : "b" }
{ "_id" : ObjectId("4caf82101b0978483ea29ae0"), "value" : "c" }
You then issue the following query:
db.items.find({value: {$gte: 97})
You may think that this query should return all six documents, since the strings are
numerically equivalent to the integers 97, 98, and 99. But this isn't the case. This
query returns the integer results only. If you want the string results, you must query
with a string instead:
db.items.find({value: {$gte: "a"})
You won't need to worry about this type restriction as long as you never store multiple
types for the same key within the same collection. This is a good general practice, and
you should abide by it.
S ET OPERATORS
Three query operators— $in , $all , and $nin —take a list of one or more values as
their predicate. $in returns a document if any of the given values matches the search
key. You might use this operator to return all products belonging to some discrete set
of categories. If the following list of category ID s
[ObjectId("6a5b1476238d3b4dd5000048"),
ObjectId("6a5b1476238d3b4dd5000051"),
ObjectId("6a5b1476238d3b4dd5000057")
]
corresponds to the lawnmowers, hand tools, and work clothing categories, then the
query to find all products belonging to these categories looks like this:
5
Note that the numeric types—integer, long integer, and double—have type equivalence for these queries.
Search WWH ::




Custom Search