partially update fields in a document - findAndModify remove all other fields?

1.1k views Asked by At

When using MongoTemplate - collection.findAndModify It will delete all document fields, and leave only the updated column/s.
Why is that?
How to partially update fields in a document?

        DBCollection collection = mongoTemplate.getCollection("company");           
        DBObject query= new BasicDBObject("companyId","1");        
        DBObject update= new BasicDBObject("phoneNumber","404-525-3928");           
        DBObject result = collection.findAndModify(query, update);


At this point - all fields removed from company 1...
The workaround will be to go to the DB, fetch company 1 document update the field/s and save it...,
But what if i need to update 10K of them?

1

There are 1 answers

1
Neil Lunn On BEST ANSWER

You need the $set operator in the update document. You use that and other update operators here otherwise what you specify will replace whatever the document currently contains:

        DBCollection collection = mongoTemplate.getCollection("company");           
        DBObject query= new BasicDBObject("companyId","1");        
        DBObject update= new BasicDBObject(
            "$set", new BasicDBObject("phoneNumber","404-525-3928")
        );          
        DBObject result = collection.findAndModify(query, update);