Database Reference
In-Depth Information
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"] } } } )
At this point, our document, which once looked tidy and trustworthy, has been transformed into something
like this:
{
"Author" :
[
"Hows, David",
"Membrey, Peter",
"Plugge, Eelco",
"Hawkins, Tim",
"Griffin, Stewie",
"Griffin, Peter",
"Griffin, Brian",
"Griffin, Louis",
"Griffin, Meg"
],
"ISBN" : "1-4302-3051-7",
"Publisher" : "Apress",
"Title" : "Definitive Guide to MongoDB, The",
"Type" : "Book",
"_id" : ObjectId("4c436231c603000000007ed0")
}
Removing Elements from an Array
MongoDB also includes several methods that let you remove elements from an array, including $pop , $pull ,
$pullAll . In the sections that follow, you'll learn how to use each of these methods for removing elements from
an array.
The $pop operator lets you remove a single element from an array. This operator lets you remove the first or last
value in the array, depending on the parameter you pass down with it. For example, the following snippet removes the
last element from the array:
> db.media.update( { "ISBN" : "1-4302-3051-7" }, {$pop : {Author : 1 } } )
 
Search WWH ::




Custom Search