如何使用mongodb-java-driver进行upsert操作

23

如何使用Java驱动程序向MongoDB集合插入数据?

我尝试(使用空集合):

db.getCollection(collection).update(new BasicDBObject("_id", "12"), dbobject, true, false);

但是该文档是使用 _id == ObjectID(...) 创建的,而不是使用 "12" 值创建的。

这段代码(js)按预期添加了 _id = "12" 的文档。

db.metaclass.update(
   { _id:12},
   {
     $set: {b:1}
   },
   { upsert: true }
)

mongo-java-driver-2.11.2


使用Jongo:http://stackoverflow.com/q/41103427/435605 - AlikElzin-kilaka
4个回答

26

如果您正在使用mongo-java驱动程序3,则使用.updateOne()方法,并带有{upsert, true}标志即可。

 void setLastIndex(MongoClient mongo, Long id, Long lastIndexValue) {

    Bson filter = Filters.eq("_id", id);

    Bson update =  new Document("$set",
                  new Document()
                        .append("lastIndex", lastIndexValue)
                        .append("created", new Date()));
    UpdateOptions options = new UpdateOptions().upsert(true);

    mongo.getDatabase(EventStreamApp.EVENTS_DB)
         .getCollection(EventCursor.name)
         .updateOne(filter, update, options);
  }

你有没有使用 $set 和 $setOnInsert 在同一个更新查询中的示例? - vivek85

18

如果dbobject只是一个文档而没有包含更新操作符(例如: $set, $setOnInsert),则无法设置_id

仅传递一个文档将取代整个文档,这意味着它不会设置_id并会回退到ObjectId

因此,如果使用更新操作符,则您的示例将起作用。

db.getCollection(collection).update(
    new BasicDBObject("_id", "12"), 
    new BasicDBObject("$set", new BasicDBObject("Hi", "world")), true, false)

3
你可以使用replaceOne方法并指定ReplaceOptions(自3.7版本起):
private static final ReplaceOptions REPLACE_OPTIONS
      = ReplaceOptions.createReplaceOptions(new UpdateOptions().upsert(true));  

db.getCollection(collection).replaceOne(new BasicDBObject("_id", "12"), dbobject, REPLACE_OPTIONS);

对于旧版本,您可以直接将UpdateOptions传递给replaceOne方法:

private static final UpdateOptions UPDATE_POLICY = new UpdateOptions().upsert(true);
db.getCollection(collection).replaceOne(new BasicDBObject("_id", "12"), dbobject, UPDATE_POLICY);  

文档所述:

replaceOne()替换集合中与筛选条件匹配的第一个文档,使用替换文档。

如果upsert: true并且没有文档与筛选条件匹配,replaceOne()会基于替换文档创建一个新文档。


-1

这是使用Scala驱动程序进行upsert操作,我在网络上找不到的

con.updateOne(  
            equal("vendor_id", vendorId),          
            inc("views_count", f.views),
            UpdateOptions().upsert(true)) 

要这样做,请导入以下内容

import org.mongodb.scala.model.UpdateOptions

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接