Spring Data MongoDB and Bulk Update

ε祈祈猫儿з 提交于 2019-12-17 16:44:43

问题


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/#Bulk.find.update

When using regular driver it looks like this:

The following example initializes a Bulk() operations builder for the items collection, and adds various multi update operations to the list of operations.

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } );
bulk.find( { item: null } ).update( { $set: { item: "TBD" } } );
bulk.execute()

Is there any way to achieve similar result with Spring Data MongoDB ?


回答1:


Bulk updates are supported from spring-data-mongodb 1.9.0.RELEASE. Here is a sample:

BulkOperations ops = template.bulkOps(BulkMode.UNORDERED, Match.class);
for (User user : users) {
    Update update = new Update();
    ...
    ops.updateOne(query(where("id").is(user.getId())), update);
}
ops.execute();



回答2:


You can use this as long as the driver is current and the server you are talking to is at least MongoDB, which is required for bulk operations. Don't believe there is anything directly in spring data right now (and much the same for other higher level driver abstractions), but you can of course access the native driver collection object that implements the access to the Bulk API:

    DBCollection collection = mongoOperation.getCollection("collection");
    BulkWriteOperation bulk = collection.initializeOrderedBulkOperation();

    bulk.find(new BasicDBObject("status","D"))
        .update(new BasicDBObject(
            new BasicDBObject(
                "$set",new BasicDBObject(
                    "status", "I"
                ).append(
                    "points", 0
                )
            )
        ));

    bulk.find(new BasicDBObject("item",null))
        .update(new BasicDBObject(
            new BasicDBObject(
                "$set", new BasicDBObject("item","TBD")
            )
        ));


    BulkWriteResult writeResult = bulk.execute();
    System.out.println(writeResult);

You can either fill in the DBObject types required by defining them, or use the builders supplied in the spring mongo library which should all support "extracting" the DBObject that they build.



来源:https://stackoverflow.com/questions/26657055/spring-data-mongodb-and-bulk-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!