我正在尝试使用文档数组作为参数调用 mongodb 的 db.collection.save 方法。如果 _id 存在,我想做批量操作插入/替换。
这是我的测试用例:
> use sometestdb
switched to db sometestdb
>
> doc1 = { _id: 1, value: "some value 1" }
{ "_id" : 1, "value" : "some value 1" }
> doc2 = { _id: 2, value: "some value 2" }
{ "_id" : 2, "value" : "some value 2" }
> doc3 = { _id: 3, value: "some value 3" }
{ "_id" : 3, "value" : "some value 3" }
>
> db.docs.save( [doc1, doc2, doc3] )
>
> doc1 = { _id: 1, value: "some value 1 - updated" }
{ "_id" : 1, "value" : "some value 1 - updated" }
> doc2 = { _id: 2, value: "some value 2 - updated" }
{ "_id" : 2, "value" : "some value 2 - updated" }
> doc3 = { _id: 3, value: "some value 3 - updated" }
{ "_id" : 3, "value" : "some value 3 - updated" }
> db.docs.save( [doc1, doc2, doc3] )
E11000 duplicate key error index: sometestdb.docs.$_id_ dup key: { : 1.0 }
如果我尝试调用db.docs.save (doc1)
,db.docs.save (doc2)
则不会引发错误。谢谢。