Database Reference
In-Depth Information
Specifying an Array of Matches with $in
The $in operator lets you specify an array of possible matches.
For instance, assume you're looking for only two kinds of development computers: not used or with
Development . Also assume that you want to limit the results to two items, returning only the ItemNumber :
>>> for doc in collection.find({"Tags" : {"$in" : ["Not used","Development"]}} ,
fields={"ItemNumber":"true"}).limit(2):
... doc
...
{u'ItemNumber': u'1234EXD', u'_id': ObjectId('4c57207b4abffe0e0c000000')}
{u'ItemNumber': u'2345FDX', u'_id': ObjectId('4c57234c4abffe0e0c000001')}
Specifying Against an Array of Matches with $nin
You use the $nin operator exactly as you use the $in operator; the difference is that this operator excludes any
documents that match any of the values specified in the given array. For example, the following query finds any items
that are currently not used in the Development department:
>>> for doc in collection.find({"Tags" : {"$nin" : ["Development"]}}, fields={"ItemNumber": True}):
... doc
...
{u'ItemNumber': u'2345FDX', u'_id': ObjectId('4c592eb84abffe0e0c000004')}
Finding Documents that Match an Array's Values
Whereas the $in operator can be used to find any document that matches any of the values specified in an array,
the $all operator lets you find any document that matches all of the values specified in an array. The syntax to
accomplish this looks exactly the same:
>>> for doc in collection.find({"Tags" : {"$all" : ["Storage","Not used"]}},
fields={"ItemNumber":"true"}):
... doc
...
{u'ItemNumber': u'2345FDX', u'_id': ObjectId('4c592eb84abffe0e0c000004')}
Specifying Multiple Expressions to Match with $or
You can use the $or operator to specify multiple values that a document can have, of which at least one must be true,
to qualify as a match. This is roughly similar to the $in operator; the difference is that the $or operator lets you specify
the key as well as the value. You can also combine the $or operator with another key/value pair. Let's look at a few
examples.
This example returns all documents that have either the location set to Storage or the owner set, to Anderson , Thomas :
>>> for doc in collection.find({"$or" : [ { "Location.Department" : "Storage" },
... { "Location.Owner" : "Anderson, Thomas"} ] } ):
... doc
...
 
Search WWH ::




Custom Search