Spring Data MongoDB and Bulk Update

后端 未结 3 584
[愿得一人]
[愿得一人] 2020-12-02 00:09

I am using Spring Data MongoDB and would like to perform a Bulk Update just like the one described here: http://docs.mongodb.org/manual/reference/method/Bulk.find.update/#Bu

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 00:24

    public  void bulkUpdate(String collectionName, List documents, Class tClass) {
        BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, tClass, collectionName);
        for (T document : documents) {
            Document doc = new Document();
            mongoTemplate.getConverter().write(document, doc);
            org.springframework.data.mongodb.core.query.Query  query = new org.springframework
                .data.mongodb.core.query.Query(Criteria.where(UNDERSCORE_ID).is(doc.get(UNDERSCORE_ID)));
            Document updateDoc = new Document();
            updateDoc.append("$set", doc);
            Update update = Update.fromDocument(updateDoc, UNDERSCORE_ID);
            bulkOps.upsert(query, update);
        }
        bulkOps.execute();
    }
    

    Spring Mongo template is used to perform the update. The above code will work if you provide the _id field in the list of documents.

提交回复
热议问题