Database Reference
In-Depth Information
Specifying Multiple Values in an Array
When working with arrays, the $push operator will append the value specified to the given array, expanding the data
stored within the given element. If you wish to add several separate values to the given array, you can use the optional
$each
modifier as in this example:
> db.media.update( { "ISBN" : "978-1-4302-5821-6" }, { $push: { Author : { $each:
["Griffin, Peter", "Griffin, Brian"] } } } )
{
"Author" :
[
"Hows, David",
"Membrey, Peter",
"Plugge, Eelco",
"Hawkins, Tim",
"Griffin, Stewie",
"Griffin, Peter",
"Griffin, Brian"
],
"ISBN" : "978-1-4302-5821-6",
"Publisher" : "Apress",
"Title" : "Definitive Guide to MongoDB 2nd ed., The",
"Type" : "Book",
"_id" : ObjectId("4c436231c603000000007ed0")
}
Optionally, you can use the
$slice
operator when using
$each
. This allows you to limit the number of elements
within an array during a
$push
operation.
$slice
takes either a negative number or zero. Using a negative number
ensures that only the last
n
elements will be kept within the array, whereas using zero would empty the array. Note
that the
$slice
operator has to be the first modifier to the
$push
operator in order to function as such:
> db.media.update( { "ISBN" : "978-1-4302-5821-6" }, { $push: { Author : { $each:
["Griffin, Meg", "Griffin, Louis"], $slice: -2 } } } )
{
"Author" :
[
"Griffin, Meg",
"Griffin, Louis"
],
"ISBN" : "978-1-4302-5821-6",
"Publisher" : "Apress",
"Title" : "Definitive Guide to MongoDB 2nd ed., The",
"Type" : "Book",
"_id" : ObjectId("4c436231c603000000007ed0")
}
As you can see, the
$slice
operator ensured that not only were the two new values pushed, the data kept within
the array was also limited to the value specified (two). The
$slice
operator can be a valuable tool when working with
fixed-sized arrays.