举个例子
拯救苹果
db.fruit.save({"name":"apple", "color":"red","shape":"round"})
WriteResult({ "nInserted" : 1 })
db.fruit.find();
{
"_id" : ObjectId("53fa1809132c1f084b005cd0"),
"color" : "red",
"shape" : "round",
"name" : "apple"
}
用以前保存的苹果的_id保存一个苹果
db.fruit.save(
{"_id" : ObjectId("53fa1809132c1f084b005cd0"),"name":"apple",
"color":"real red","shape":"round"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
现在我们保存的苹果有了,颜色从红色更新为真正的红色
db.fruit.find();
{
"_id" : ObjectId("53fa1809132c1f084b005cd0"),
"color" : "real red",
"shape" : "round",
"name" : "apple"
}
用_id保存一个苹果
db.fruit.save({"_id" : ObjectId("55551809132c1f084b005cd0"),
"name":"apple", "color":"real red","shape":"round"})
WriteResult({ "nMatched" : 0, "nUpserted" : 1,
"nModified" : 0, "_id": 55551809132c1f084b005cd0 })
Apple 被插入,因为没有具有相同 Object Id 的苹果进行更新
插入橙色
db.fruit.insert({"name":"orange", "color":"orange","shape":"round"})
WriteResult({ "nInserted" : 1 })
插入橙色
db.fruit.find();
{
"_id" : ObjectId("53fa1809132c1f084b005cd0"),
"color" : "real red",
"shape" : "round",
"name" : "apple"
}
{
"_id" : ObjectId("53fa196d132c1f084b005cd7"),
"color" : "orange",
"shape" : "round",
"name" : "orange"
}
{
"_id" : ObjectId("55551809132c1f084b005cd0"),
"color" : "real red",
"shape" : "round",
"name" : "apple"
}
因此,如果提供了对象 ID,则保存将充当更新,前提是该对象 ID 已经存在,否则它会执行插入。