Bulk Upsert with MongoDB Java 3.0 Driver

后端 未结 3 803
感情败类
感情败类 2020-12-25 08:50

In the earlier versions of MongoDB Java drivers , to run a query and do unordered bulk upsert on the result all we had do was :

BulkWriteOperation bulk = dbC         


        
3条回答
  •  梦谈多话
    2020-12-25 09:31

    You can still use all of the functionality, it's just that BulkWrites now have a different syntax:

        MongoCollection collection = db.getCollection("sample");
    
        List> updates = Arrays.>asList(
            new UpdateOneModel(
                    new Document(),                   // find part
                    new Document("$set",1),           // update part
                    new UpdateOptions().upsert(true)  // options like upsert
            )
        );
    
        BulkWriteResult bulkWriteResult = collection.bulkWrite(updates);
    

    So you use the UpdateOneModel ( or for many if you want ) and set the UpdateOptions as the third argument to the constructor.

    Takes some getting used to, but it's basically just building "Lists" with all the same syntax as elsewhere. I guess that's the main reason for the change.

提交回复
热议问题