Search code examples
mongodbmongodb-java

Update a MongoDB document in JAVA without explicit conversion


I am using the mongo-db java driver 3.8 and work with the collection as follows:

MongoDatabase md=mongoClient.getDatabase(databaseName);
MongoCollection<ConstructionPlan> collection=md.getCollection(plansCollectionName,abc.class);
collection.insertOne(item);
collection.find(Filters.eq("itemId", id),abc.class).first();

With this code I do not have to do any conversion. I was looking for a way to update an document the same way. I am thinking on something like this:

abc anABCObject=collection.find(Filters.eq("itemId", id),ConstructionPlan.class).first();
//updates...
collection.update(anABCObject);

Is there a way to update an existing document without BSON conversion? (I was unable to find it....)


Solution

  • updateOne for updating document fields using update operators.

    You need replaceOne which takes the replacement document.

    collection.replaceOne(
       Filters.eq("itemId", id),
       anABCObject
    );