英文:
Use WriteConcern in MongoCollection.deleteMany in mongo-java-driver 3.12
问题
我正在使用mongo-java-driver-3.12.X版本。
我想要将被弃用的API进行更改
DBCollection.remove(query, WriteConcern.UNACKNOWLEDGED);
为
MongoCollection.deleteMany(query);
- 是否有一种方法可以指定WriteConcern?
- 如果未指定WriteConcern,将会有什么默认行为?
英文:
I am using mongo-java-driver-3.12.X version.
I want to change the deprecated API
DBCollection.remove(query, WriteConcern.UNACKNOWLEDGED);
to
MongoCollection.deleteMany(query)
- Is there a way to specify WriteConcern?
- What will be the default behaviour if WriteConcern is not specified?
答案1
得分: 1
你可以在驱动程序文档中轻松找到这些信息。
对于3.12版本,可以将WriteConcern设置为多个级别,如下所示。
MongoClient:
MongoClientOptions options = MongoClientOptions.builder().writeConcern(WriteConcern.UNACKNOWLEDGED).build();
MongoClient mongoClient = new MongoClient(Arrays.asList(
new ServerAddress("host1", 27017),
new ServerAddress("host1", 27018)), options);
或者使用连接字符串
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://host1:27017,host2:27017/?w=unacknowledged"));
MongoDatabase
MongoDatabase database = mongoClient.getDatabase("test").withWriteConcern(WriteConcern.UNACKNOWLEDGED);
MongoCollection
这是您感兴趣的情况
MongoCollection<Document> collection = database.getCollection("restaurants").withWriteConcern(WriteConcern.UNACKNOWLEDGED);
collection.deleteMany(query);
请记住,MongoCollection和MongoDatabase是不可变的,因此调用withWriteConcern会创建一个新实例,并且不会影响原始实例。
有关默认行为,您需要查看文档,因为它取决于您的mongodb版本。
英文:
You can easily find this information in the driver documentation.
WriteConcern can be set to multiple level for 3.12 version it goes like this.
MongoClient:
MongoClientOptions options = MongoClientOptions.builder().writeConcern(WriteConcern.UNACKNOWLEDGED).build();
MongoClient mongoClient = new MongoClient(Arrays.asList(
new ServerAddress("host1", 27017),
new ServerAddress("host1", 27018)), options);
or with a connection string
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://host1:27017,host2:27017/?w=unacknowledged"));
MongoDatabase
MongoDatabase database = mongoClient.getDatabase("test").withWriteConcern(WriteConcern.UNACKNOWLEDGED);
MongoCollection
This is the case you are interested in
MongoCollection<Document> collection = database.getCollection("restaurants").withWriteConcern(WriteConcern.UNACKNOWLEDGED);
collection.deleteMany(query);
Keep in mind that MongoCollection and MongoDatabase are immutable so calling withWriteConcern create a new instance and has no effect on the original instance.
For the default behavior you need to check the documentation because it depends on your mongodb version.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论