Database Reference
In-Depth Information
Removing Each Occurrence of a Specified Value
The $pull operator lets you remove each occurrence of a specified value from an array.
This can be particularly useful if you have multiple elements with the same value in your
array. Let's begin this example by using the $push parameter to add Stewie back to the list
of authors:
> db.media.update ( {"ISBN" : "1-4302-3051-7"}, {$push: { Author :
"Griffin, Stewie"} } )
Stewie will be in and out of the database a couple more times as we walk through this
book's examples. You can remove all occurrences of this author in the document with the
following code:
> db.media.update ( {"ISBN" : "1-4302-3051-7"}, {$pull : { Author :
"Griffin,
Stewie" } } )
Removing Multiple Elements from an Array
You can also remove multiple elements with different values from an array. The $pullAll
operator enables you to accomplish this. The $pullAll operator takes an array with all
the elements you want to remove, as in the following example:
> db.media.update( { "ISBN" : "1-4302-3051-7"}, {$pullAll : { Author :
["Griffin, Louis","Griffin, Peter","Griffin, Brian"] } } )
The field from which you remove the elements ( Author in the preceding example)
needs to be an array. If it isn't, you'll receive an error message.
Specifying the Position of a Matched Array
You can use the $ operator in your queries to specify the position of the matched array
item in your query. You can use this operator for data manipulation after finding an array
member. For instance, assume you've added another track to your track list, but you
accidently made a typo when entering the track number:
> db.media.update( { "Title" : "Nirvana" }, {$addToSet : { Tracklist :
{"Track" : 2,"Title": "Been a Son", "Length":"2:23"} } } )
{
"Artist" : "Nirvana",
"Title" : "Nirvana",
 
Search WWH ::




Custom Search