2013-06-26 51 views
13

如何使用java-driver将数据插入到mongodb集合中?如何使用mongodb-java驱动程序进行插入

我尝试(空集):

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

但文件与创建_id ==对象ID(...)。不带“12”值。

此代码(JS)与预期

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

蒙戈-java的驱动程序2.11.2

+0

使用Jongo:http://stackoverflow.com/q/41103427/435605 –

回答

14

不能_id如果dbobject设置仅仅是一个文档,_id = “12” 添加文件不包含更新运算符,例如:$set,$setOnInsert

刚好路过的文件将取代整个文档这意味着它不会设置_id一个回落到ObjectId

所以如果你使用的更新操作如您示例工作:

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

如果您使用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

任何在同一个更新查询,你将如何使用$设置例如和$ setOnInsert。 – vivek85

相关问题