Database Reference
In-Depth Information
$inc is as efficient as it is convenient. Because it rarely changes the size of a document,
an $inc usually occurs in-place on disk, thus affecting only the value pair specified. 8
As demonstrated in the code for adding products to a shopping cart, $inc works
with upserts. For example, you can change the preceding update to an upsert like so:
db.readings.update({_id: 324}, {$inc: {temp: 2.7435}}, true)
If no reading with an _id of 324 exists, a new document will be created with said _id
and a temp with the value of the $inc , 2.7435.
$set and $unset
If you need to set the value of a particular key in a document, you'll want to use $set .
You can set a key to a value having any valid BSON type. This means that all of the fol-
lowing updates are possible:
db.readings.update({_id: 324}, {$set: {temp: 97.6}})
db.readings.update({_id: 325}, {$set: {temp: {f: 212, c: 100} })
db.readings.update({_id: 326}, {$set: {temps: [97.6, 98.4, 99.1]}})
If the key being set already exists, then its value will be overwritten; otherwise, a new
key will be created.
$unset removes the provided key from a document. Here's how to remove the
temp key from the reading document:
db.readings.update({_id: 324}, {$unset: {temp: 1})
You can also use $unset on embedded documents and on arrays. In both cases, you
specify the inner object using dot notation. If you have these two documents in your
collection
{_id: 325, 'temp': {f: 212, c: 100}}
{_id: 326, temps: [97.6, 98.4, 99.1]}
then you can remove the Fahrenheit reading in the first document and the zeroth ele-
ment in the second document like so:
db.readings.update({_id: 325},
{$unset: {'temp.f': 1}})
db.readings.update({_id: 236},
{$pop: {temps: -1})
This dot notation for accessing sub-documents and array elements can also be used
with $set .
$rename
If you need to change the name of a key, use $rename :
db.readings.update({_id: 324}, {$rename: {'temp': 'temperature'})
You can also rename a sub-document:
db.readings.update({_id: 325}, {$rename: {'temp.f': 'temp.farenheit'})
8
Exceptions to this rule arise when the numeric type changes. If the $inc results in a 32-bit integer being con-
verted to a 64-bit integer, then the entire BSON document will have to be rewritten in-place.
Search WWH ::




Custom Search