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

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

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

只是传递一个文档将替换整个文档意味着它没有设置_id回退到ObjectId

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

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

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