When performing updates on objects in MongoDB, you need to specify exactly what fields need to be changed and how they need to be changed. Unlike in SQL, where you create long query strings to define an update, in MongoDB you can implement an update
object with operators that define exactly how to change the data in the documents.
You can include as many operators in the update
object as you need. The format of the update
object is shown below:
{
<operator>: {<field_operation>, <field_operation>, . . .},
<operator>: {<field_operation>, <field_operation>, . . .}
. . .
}
For example, consider the following object:
{
name: "myName",
countA: 0,
countB: 0,
days: ["Monday", "Wednesday"],
scores: [ {id:"test1", score:94}, {id:"test2", score:85}, {id:"test3", score:97}]
}
Use the following update
object if you want to increment the countA
field by 5
, increment countB
by 1
, set name
to "New Name"
, add Friday
to the days
array, and sort the scores
array by the score
field:
{
$inc:{countA:5, countB:1},
$set:{name:"New Name"},
$push{days:"Friday},
$sort:{score:1}
}
Table 14.2 lists the operators you can use in the update
object to update documents.