【问题标题】:How to upsert with mongodb-java-driver如何使用 mongodb-java-driver 进行 upsert
【发布时间】:2013-06-23 13:07:54
【问题描述】:

如何使用 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

【问题讨论】:

标签: java mongodb upsert


【解决方案1】:

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

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

因此,如果您使用更新运算符,您的示例将有效,例如:

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

【讨论】:

    【解决方案2】:

    如果您使用的是mongo-java driver 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);
      }
    

    【讨论】:

    • 在同一更新查询中如何使用 $set 和 $setOnInsert 的任何示例。
    【解决方案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);  
    

    documentation 中所述:

    replaceOne() 替换集合中的第一个匹配文档 匹配过滤器,使用替换文档。

    如果 upsert: true 并且没有文档匹配过滤器,replaceOne() 根据替换文档创建一个新文档。

    【讨论】:

      【解决方案4】:

      这是为了使用我在 web 中找不到的 scala 驱动程序进行更新

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

      为此,请导入以下内容

      import org.mongodb.scala.model.UpdateOptions
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-24
        • 1970-01-01
        相关资源
        最近更新 更多