0

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?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159

1 Answers1

1

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);
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • working great thank you! I used collection.update(query,new BasicDBObject( "$set", new BasicDBObject("phoneNumber","404-525-3928")) – JavaSheriff Nov 12 '14 at 00:56