javamongodbmongodb-javamongo-java-drivermongo-collection

Use WriteConcern in MongoCollection.deleteMany in mongo-java-driver 3.12


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)
  1. Is there a way to specify WriteConcern?
  2. What will be the default behaviour if WriteConcern is not specified?

Solution

  • 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.