Databases Reference
In-Depth Information
If you want to query for a specific element of an array, you can specify an index using
the syntax
key
.
index
:
> db.food.find({"fruit.2" : "peach"})
Arrays are always 0-indexed, so this would match the third array element against the
string
"peach"
.
$size
A useful conditional for querying arrays is
"$size"
, which allows you to query for arrays
of a given size. Here's an example:
> db.food.find({"fruit" : {"$size" : 3}})
One common query is to get a range of sizes.
"$size"
cannot be combined with another
$ conditional (in this example,
"$gt"
), but this query can be accomplished by adding
a
"size"
key to the document. Then, every time you add an element to the array, in-
crement the value of
"size"
. If the original update looked like this:
> db.food.update({"$push" : {"fruit" : "strawberry"}})
it can simply be changed to this:
> db.food.update({"$push" : {"fruit" : "strawberry"}, "$inc" : {"size" : 1}})
Incrementing is extremely fast, so any performance penalty is negligible. Storing docu-
ments like this allows you to do queries such as this:
> db.food.find({"size" : {"$gt" : 3}})
Unfortunately, this technique doesn't work as well with the
"$addToSet"
operator.
The $slice operator
As mentioned earlier in this chapter, the optional second argument to
find
specifies
the keys to be returned. The special
"$slice"
operator can be used to return a subset
of elements for an array key.
For example, suppose we had a blog post document and we wanted to return the first
10 comments:
> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : 10}})
Alternatively, if we wanted the last 10 comments, we could use -10:
> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : -10}})
"$slice"
can also return pages in the middle of the results by taking an offset and the
number of elements to return:
> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : [23, 10]}})
This would skip the first 23 elements and return the 24th through 34th. If there are
fewer than 34 elements in the array, it will return as many as possible.