Databases Reference
In-Depth Information
If we look at the document after this update, we'll see the following:
> db.games.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 50
}
The score key did not already exist, so it was created by "$inc" and set to the increment
amount: 50.
If the ball lands in a “bonus” slot, we want to add 10,000 to the score. This can be
accomplished by passing a different value to "$inc" :
> db.games.update({"game" : "pinball", "user" : "joe"},
... {"$inc" : {"score" : 10000}})
Now if we look at the game, we'll see the following:
> db.games.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 10050
}
The "score" key existed and had a numeric value, so the server added 10,000 to it.
"$inc" is similar to "$set" , but it is designed for incrementing (and decrementing)
numbers. "$inc" can be used only on values of type integer, long, or double. If it is used
on any other type of value, it will fail. This includes types that many languages will
automatically cast into numbers, like nulls, booleans, or strings of numeric characters:
> db.foo.insert({"count" : "1"})
> db.foo.update({}, {$inc : {count : 1}})
Cannot apply $inc modifier to non-number
Also, the value of the "$inc" key must be a number. You cannot increment by a string,
array, or other non-numeric value. Doing so will give a “Modifier "$inc" allowed for
numbers only” error message. To modify other types, use "$set" or one of the array
operations described in a moment.
Array modifiers
An extensive class of modifiers exists for manipulating arrays. Arrays are common and
powerful data structures: not only are they lists that can be referenced by index, but
they can also double as sets.
Array operators can be used only on keys with array values. For example, you cannot
push on to an integer or pop off of a string, for example. Use "$set" or "$inc" to modify
scalar values.
 
Search WWH ::




Custom Search