mongodbupsertmultiple-insert

insert each object in the list, update it if it exists already


I still have problems with insert/update of multiple items. The thing is I have a list of N items, each of which (item) I want to insert. But if an item with the same unique key already exists, I want to have it updated instead. (An item contains a unique key.) So basically I want to upsert each individual item using a single roundtrip.

Of course I can do this item by item, but I wish I could do this using a batch, so I don't need N roundtrips.

Is there a way of doing this (Java)?


Solution

  • this is what works:

    public static BulkWriteResult upsertAll(MongoCollection<Document> coll, List<Document> docs, String keyTag) {
        List<UpdateOneModel<Document>> requests = new ArrayList<UpdateOneModel<Document>>();
        UpdateOptions opt = new UpdateOptions().upsert(true);
        for (Document doc : docs ) {
            BasicDBObject filter = new BasicDBObject(keyTag, doc.get(keyTag)); 
            BasicDBObject action = new BasicDBObject("$set", doc);
            requests.add(new UpdateOneModel<Document>(filter, action, opt));
        }
        return coll.bulkWrite(requests);
    }