Databases Reference
In-Depth Information
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"username" : "joe",
"emails" : [
"joe@example.com",
"joe@gmail.com",
"joe@yahoo.com",
"joe@hotmail.com"
"joe@php.net"
"joe@python.org"
]
}
There are a few ways to remove elements from an array. If you want to treat the array
like a queue or a stack, you can use "$pop" , which can remove elements from either
end. {$pop : { key : 1}} removes an element from the end of the array. {$pop :
{ key : -1}} removes it from the beginning.
Sometimes an element should be removed based on specific criteria, rather than its
position in the array. "$pull" is used to remove elements of an array that match the
given criteria. For example, suppose we have a list of things that need to be done but
not in any specific order:
> db.lists.insert({"todo" : ["dishes", "laundry", "dry cleaning"]})
If we do the laundry first, we can remove it from the list with the following:
> db.lists.update({}, {"$pull" : {"todo" : "laundry"}})
Now if we do a find, we'll see that there are only two elements remaining in the array:
> db.lists.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"todo" : [
"dishes",
"dry cleaning"
]
}
Pulling removes all matching documents, not just a single match. If you have an array
that looks like [1, 1, 2, 1] and pull 1 , you'll end up with a single-element array, [2] .
Positional array modifications
Array manipulation becomes a little trickier when we have multiple values in an array
and want to modify some of them. There are two ways to manipulate values in arrays:
by position or by using the position operator (the "$" character).
Arrays use 0-based indexing, and elements can be selected as though their index were
a document key. For example, suppose we have a document containing an array with
a few embedded documents, such as a blog post with comments:
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b329a216cc613d5ee930192"),
 
Search WWH ::




Custom Search