繁体   English   中英

如何使用 mongodb-java-driver 进行更新插入

[英]How to upsert with mongodb-java-driver

如何使用 java-driver 将数据更新到 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

如果您使用的是mongo-java 驱动程序 3 ,则遵循带有{upsert, true}标志的.updateOne()方法有效。

 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);
  }

如果dbobject只是一个文档并且不包含更新运算符,例如: $set$setOnInsert ,则不能设置_id

只是传递一个文档将替换整个文档,这意味着它不会设置_id回退到ObjectId

因此,如果您使用更新运算符,例如:

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

您可以使用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() 根据替换文档创建一个新文档。

This is to upsert with scala driver which i couldnot find in web

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

to do so import the following
import org.mongodb.scala.model.UpdateOptions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM