Database Reference
In-Depth Information
Importantly, this query can take advantage of an index on the tags field. So if you
build the required index and run your query with explain() , you'll see that a B-tree
cursor is used:
db.products.ensureIndex({tags: 1})
db.products.find({tags: "soil"}).explain()
When you need more control over your array queries, you can use dot notation to
query for a value at a particular position within the array. Here's how you'd restrict the
previous query to the first of a product's tags:
db.products.find({'tags.0': "soil"})
It might not make much sense to query tags in this way, but imagine you're dealing
with user addresses. These you might represent with an array of sub-documents:
{ _id: ObjectId("4c4b1476238d3b4dd5000001")
username: "kbanker",
addresses: [
{name: "home",
street: "588 5th Street",
city: "Brooklyn",
state: "NY",
zip: 11215},
{name: "work",
street: "1 E. 23rd Street",
city:
"New York",
state
"NY",
zip
10010},
]
}
You might stipulate that the zeroth element of the array always be the user's primary
shipping address. Thus, to find all users whose primary shipping address is in New
York, you could again specify the zeroth position and combine that with a dot to target
the state field:
db.users.find({'addresses.0.state': "NY"})
You can just as easily omit the position and specify a field alone. The following query
will return a user document if any of the addresses in the list is in New York:
db.users.find({'addresses.state': "NY"})
As before, you'll want to index this dotted field:
db.users.ensureIndex({'addresses.state': 1})
Note that you use the same dot notation regardless of whether a field points to a sub-
document or to an array of sub-documents. This is powerful, and the consistency is
reassuring. But ambiguity can arise when querying against more than one attribute
within an array of sub-objects. For example, suppose you want to fetch a list of all users
whose home address is in New York. Can you think of a way to express this query?
db.users.find({'addresses.name': 'home', 'addresses.state': 'NY'})
Search WWH ::




Custom Search