Database Reference
In-Depth Information
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.
Adding Data to an Array with $addToSet
The $addToSet operator is another command that lets you add data to an array. However,
this operator only adds the data to the array if the data is not already there. In this way,
$addToSet is unlike $push . By default, the $addToSet operator takes one argument.
However, you can use the $each operator to specify additional arguments when using
t $addToSet . The following snippet adds the author Griffin, Brian into the authors array
because it isn't there yet:
> db.media.update( { "ISBN" : "1-4302-3051-7" }, {$addToSet : { Author :
"Griffin, Brian" } } )
Executing the snippet again won't change anything because the author is already in
the array.
To add more than one value, however, you should take a different approach and use
the $each operator, as well:
> db.media.update( { "ISBN" : "1-4302-3051-7" }, {$addToSet : { Author :
{ $each : ["Griffin, Brian","Griffin, Meg"] } } } )
 
Search WWH ::




Custom Search