Databases Reference
In-Depth Information
"$push" adds an element to the end of an array if the specified key already exists and
creates a new array if it does not. For example, suppose that we are storing blog posts
and want to add a "comments" key containing an array. We can push a comment onto
the nonexistent "comments" array, which will create the array and add the comment:
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "..."
}
> db.blog.posts.update({"title" : "A blog post"}, {$push : {"comments" :
... {"name" : "joe", "email" : "joe@example.com", "content" : "nice post."}}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "...",
"comments" : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "nice post."
}
]
}
Now, if we want to add another comment, we can simple use "$push" again:
> db.blog.posts.update({"title" : "A blog post"}, {$push : {"comments" :
... {"name" : "bob", "email" : "bob@example.com", "content" : "good post."}}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "...",
"comments" : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "nice post."
},
{
"name" : "bob",
"email" : "bob@example.com",
"content" : "good post."
}
]
}
A common use is wanting to add a value to an array only if the value is not already
present. This can be done using a "$ne" in the query document. For example, to push
an author onto a list of citations, but only if he isn't already there, use the following:
 
Search WWH ::




Custom Search