Come posso inviare i dati nella raccolta mongodb con java-driver?
Provo (con la raccolta vuota):
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) aggiunge un documento con _id = "12" come previsto
db.metaclass.update(
{ _id:12},
{
$set: {b:1}
},
{ upsert: true }
)
mongo-java-driver-2.11.2
risposte:
14 per risposta № 1Non puoi impostare _id
Se dbobject
è solo un documento e non contiene un operatore di aggiornamento ad esempio: $set
, $setOnInsert
.
Il semplice passaggio di un documento sostituirà il intero documento il che significa che non imposta un _id
a ricade su ObjectId
Quindi il tuo esempio funziona se usi un operatore di aggiornamento ad esempio:
db.getCollection(collection).update(
new BasicDBObject("_id", "12"),
new BasicDBObject("$set", new BasicDBObject("Hi", "world")), true, false)
16 per risposta № 2
Se stai usando driver mongo-java 3, a seguire .updateOne
metodo con {upsert, true}
bandiera 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)
}