Databases Reference
In-Depth Information
> joe.username = joe.name;
"joe"
> delete joe.friends;
true
> delete joe.enemies;
true
> delete joe.name;
true
> db.users.update({"name" : "joe"}, joe);
Now, doing a findOne shows that the structure of the document has been updated.
A common mistake is matching more than one document with the criteria and then
create a duplicate "_id" value with the second parameter. The database will throw an
error for this, and nothing will be changed.
For example, suppose we create several documents with the same "name" , but we don't
realize it:
> db.people.find()
{"_id" : ObjectId("4b2b9f67a1f631733d917a7b"), "name" : "joe", "age" : 65},
{"_id" : ObjectId("4b2b9f67a1f631733d917a7c"), "name" : "joe", "age" : 20},
{"_id" : ObjectId("4b2b9f67a1f631733d917a7d"), "name" : "joe", "age" : 49},
Now, if it's Joe #2's birthday, we want to increment the value of his "age" key, so we
might say this:
> joe = db.people.findOne({"name" : "joe", "age" : 20});
{
"_id" : ObjectId("4b2b9f67a1f631733d917a7c"),
"name" : "joe",
"age" : 20
}
> joe.age++;
> db.people.update({"name" : "joe"}, joe);
E11001 duplicate key on update
What happened? When you call update, the database will look for a document match-
ing {"name" : "joe"} . The first one it finds will be the 65-year-old Joe. It will attempt
to replace that document with the one in the joe variable, but there's already a docu-
ment in this collection with the same "_id" . Thus, the update will fail, because "_id"
values must be unique. The best way to avoid this situation is to make sure that your
update always specifies a unique document, perhaps by matching on a key like "_id" .
Using Modifiers
Usually only certain portions of a document need to be updated. Partial updates can
be done extremely efficiently by using atomic update modifiers . Update modifiers are
special keys that can be used to specify complex update operations, such as altering,
adding, or removing keys, and even manipulating arrays and embedded documents.
Suppose we were keeping website analytics in a collection and wanted to increment a
counter each time someone visited a page. We can use update modifiers to do this
 
Search WWH ::




Custom Search