首页 文章

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

提问于
浏览
17

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

蒙戈-java的驱动程序2.11.2

3 回答

  • 17

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

    只是传递一个文件将取代 whole document 意味着它没有设置 _id 一个回落到 ObjectId

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

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

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

    您可以使用 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);
    

    如_2739339中所述:

    replaceOne()使用替换文档替换集合中与筛选器匹配的第一个匹配文档 . 如果upsert:true且没有文档与过滤器匹配,则replaceOne()根据替换文档创建新文档 .

相关问题