2013-06-26 6 views
13

Come posso inviare i dati nella raccolta mongodb con java-driver?Come eseguire l'upsert con mongodb-java-driver

provo (con la collezione vuoto):

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

Ma il documento è stato creato con _id == ObjectID (...). Non con valore "12".

Questo codice (js) aggiungere documento con _ID = "12" come previsto

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

mongo-java-driver-2.11.2

+0

Utilizzando Jongo: http://stackoverflow.com/q/41103427/435605 –

risposta

14

Non è possibile impostare _id se dbobject è solo un documento e non contiene un operatore di aggiornamento ad esempio: $set, $setOnInsert.

Solo di passaggio di un documento andrà a sostituire l'intero documento significa che non imposta un _id A cade di nuovo a ObjectId

Così il vostro esempio funziona se si utilizza un operatore ad es aggiornamento:

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

Se si utilizza mongo-java driver 3, il seguente metodo .updateOne con il flag {upsert, true} funziona.

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

Qualsiasi esempio di come userete $ set e $ setOnInsert nella stessa query di aggiornamento. – vivek85