Databases Reference
In-Depth Information
"content" : "...",
"comments" : [
{
"comment" : "good post",
"author" : "John",
"votes" : 0
},
{
"comment" : "i thought it was too short",
"author" : "Claire",
"votes" : 3
},
{
"comment" : "free watches",
"author" : "Alice",
"votes" : -1
}
]
}
If we want to increment the number of votes for the first comment, we can say the
following:
> db.blog.update({"post" : post_id},
... {"$inc" : {"comments.0.votes" : 1}})
In many cases, though, we don't know what index of the array to modify without
querying for the document first and examining it. To get around this, MongoDB has a
positional operator, "$" , that figures out which element of the array the query document
matched and updates that element. For example, if we have a user named John who
updates his name to Jim, we can replace it in the comments by using the positional
operator:
db.blog.update({"comments.author" : "John"},
... {"$set" : {"comments.$.author" : "Jim"}})
The positional operator updates only the first match. Thus, if John had left more than
one comment, his name would be changed only for the first comment he left.
Modifier speed
Some modifiers are faster than others. $inc modifies a document in place: it does not
have to change the size of a document, only the value of a key, so it is very efficient. On
the other hand, array modifiers might change the size of a document and can be slow.
( "$set" can modify documents in place if the size isn't changing but otherwise is subject
to the same performance limitations as array operators.)
MongoDB leaves some padding around a document to allow for changes in size (and,
in fact, figures out how much documents usually change in size and adjusts the amount
of padding it leaves accordingly), but it will eventually have to allocate new space for
a document if you make it much larger than it was originally. Compounding this
 
Search WWH ::




Custom Search