Database Reference
In-Depth Information
In this case, the $pop operator will pop Meg's name off the list of authors. Passing down a negative number would
remove the first element from the array. The following example removes Peter Membrey's name from the list of authors:
> db.media.update( { "ISBN" : "1-4302-3051-7" }, {$pop : {Author : -1 } } )
Specifying a value of -2 or 1000 wouldn't change which element gets removed. any negative number would
remove the first element, while any positive number would remove the last element. Using the number 0 removes the last
element from the array.
Note
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 topic'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