When we use MongoDB’s update, if we set the third parameter to true, a new document will be created if no document is found. The following is an example:
>db.foo.find()
{ “_id” : ObjectId(“4e9165cf717ed94f8289ac0c”), “bar” :
“baz”}
>db.foo.update({“bar”:”baz”}, {“$inc”:{“count”:3}})
>db.foo.find()
{ “_id” : ObjectId(“4e9165cf717ed94f8289ac0c”), “bar” :
“baz”, “count” : 3 }
>db.foo.update({“bar”:”bazz”}, {“$inc”:{“count”:3}})
>db.foo.find()
{ “_id” : ObjectId(“4e9165cf717ed94f8289ac0c”), “bar” :
“baz”, “count” : 3 }
> db.foo.update({“bar”:”bazz”},
{“$inc”:{“count”:3}},true)
> db.foo.find()
{ “_id” : ObjectId(“4e9165cf717ed94f8289ac0c”), “bar” :
“baz”, “count” : 3 }
{ “_id” : ObjectId(“4e916661739f1da5452a4dfe”), “bar” :
“bazz”, “count” : 3 }
If the third parameter is not set to true in update, no action will be taken when the document to be updated cannot be found; if the third parameter is set to true, a new document will be created if no document is found.