如何使用mongodb-java-driver进行upsert [英] How to upsert with mongodb-java-driver
问题描述
如何使用java-driver将数据插入mongodb集合?
How can I upsert data into mongodb collection with java-driver?
我尝试(使用空集合):
I try (with empty collection):
db.getCollection(collection).update(new BasicDBObject("_id", "12"), dbobject, true, false);
但文档是使用_id == ObjectID(...)创建的。不是12值。
But document was created with _id == ObjectID(...). Not with "12" value.
此代码(js)按预期添加_id =12的文档
This code (js) add document with _id = "12" as expected
db.metaclass.update(
{ _id:12},
{
$set: {b:1}
},
{ upsert: true }
)
mongo-java-driver-2.11 .2
mongo-java-driver-2.11.2
推荐答案
如果 _id
> dbobject 只是一个文档,不包含更新运算符,例如: $ set
, $ setOnInsert
。
You cannot set _id
if dbobject
is just a document and does not contain an update operator eg: $set
, $setOnInsert
.
只是传递一个文件将取代整个文件,这意味着它没有设置 _id
a回退到 ObjectId
Just passing a document will replace the whole document meaning it doesn't set an _id
a falls back to ObjectId
因此,如果您使用更新运算符,则示例有效:
So your example works if you use an update operator eg:
db.getCollection(collection).update(
new BasicDBObject("_id", "12"),
new BasicDBObject("$set", new BasicDBObject("Hi", "world")), true, false)
这篇关于如何使用mongodb-java-driver进行upsert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!