Database Reference
In-Depth Information
Finally, when specifying a negative integer, you can skip to the last five items and
limit the results to four, as in this example:
> db.media.find({"Title" : "Matrix, The"}, {"Cast" : {$slice: [-5,4] }})
{ "_id" : ObjectId("4c5fcd3edb290000000067cb"), "Type" : "DVD", "Title" :
"Matrix, The", "Released" : 1999, "Cast" : [ "Carrie-Anne Moss","Laurence
Fishburne","Hugo Weaving","Gloria Foster"] }
With version 2.4 MongoDB also introduced the $slice operator for $push
operations, allowing you to limit the number of array elements when appending values to an
array. this operator is discussed later in this chapter. Do not confuse the two, however.
Note
Searching for Odd/Even Integers
The $mod operator lets you search for specific data that consists of an even or uneven
number. This works because the operator takes the modulus of 2 and checks for a
remainder of 0 , thereby providing even-numbered results only.
For example, the following code returns any item in the collection that has an even-
numbered integer set to its Released field:
> db.media.find ( { Released : { $mod: [2,0] } }, {"Cast" : 0 } )
{ "_id" : ObjectId("4c45b5c18e0f0000000062aa"), "Type" : "DVD", "Title" :
"Blade Runner", "Released" : 1982 }
{ "_id" : ObjectId("4c45b5df8e0f0000000062ab"), "Type" : "DVD", "Title" :
"Toy Story 3", "Released" : 2010 }
Likewise, you can find any documents containing an uneven value in the Released
field by changing the parameters in $mod , as follows:
> db.media.find ( { Released : { $mod: [2,1] } }, { "Cast" : 0 } )
{ "_id" : ObjectId("4c45b5b38e0f0000000062a9"), "Type" : "DVD", "Title" :
"Matrix, The", "Released" : 1999 }
the $mod operator only works on integer values, not on strings that contain a
numbered value. For example, you can't use the operator on { Released : "2010" } ,
because it's in quotes and therefore a string.
Note
 
 
Search WWH ::




Custom Search