Databases Reference
In-Depth Information
Getting started with the "$set" modifier
"$set"
sets the value of a key. If the key does not yet exist, it will be created. This can
be handy for updating schema or adding user-defined keys. For example, suppose you
have a simple user profile stored as a document that looks something like the following:
> db.users.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"name" : "joe",
"age" : 30,
"sex" : "male",
"location" : "Wisconsin"
}
This is a pretty bare-bones user profile. If the user wanted to store his favorite topic in
his profile, he could add it using
"$set"
:
> db.users.update({"_id" : ObjectId("4b253b067525f35f94b60a31")},
... {"$set" : {"favorite book" : "war and peace"}})
Now the document will have a “favorite book” key:
> db.users.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"name" : "joe",
"age" : 30,
"sex" : "male",
"location" : "Wisconsin",
"favorite book" : "war and peace"
}
If the user decides that he actually enjoys a different topic,
"$set"
can be used again to
change the value:
> db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" : "green eggs and ham"}})
"$set"
can even change the type of the key it modifies. For instance, if our fickle user
decides that he actually likes quite a few topics, he can change the value of the “favorite
topic” key into an array:
> db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" :
... ["cat's cradle", "foundation trilogy", "ender's game"]}})
If the user realizes that he actually doesn't like reading, he can remove the key altogether
with
"$unset"
:
> db.users.update({"name" : "joe"},
... {"$unset" : {"favorite book" : 1}})
Now the document will be the same as it was at the beginning of this example.