A significant difference between MongoDB & RDBMS is MongoDB has many kinds of operators. One of them is update operator, which is used in update statements.
Suppose we have a student collection to store student information(Table view):
One day you get a job that need to change Tom's gender from "M" to "F". That's easy, right? So you write below statement very quickly based on your RDBMS experience:
db.student.update(
{name: 'Tom'}, // query criteria
{sex: 'F'} // update action
);
We lost Tom's age & name! From this example, we can know that the whole document will be overrided if without any update operator in update statement. This is the default behavior of MongoDB.
If we want to change only the 'sex' field in Tom's document, we can use $set
to specify which field(s) we want to update:
db.student.update(
{name: 'Tom'}, // query criteria
{$set: {sex: 'F'}} // update action
);
The value of $set
is an object, its fields stands for those fields you want to update in the documents, and the values of these fields are the target values.
So, the result is correct now:
Also, if you want to change both 'sex' and 'age' at the same time, you can append them to $set
:
db.student.update(
{name: 'Tom'}, // query criteria
{$set: {sex: 'F', age: 40}} // update action
);