From the MongoDB documentation:
If the update argument contains only pairs of fields and values, the update () method replaces the existing document with the document in the update argument, except for the _id field.
In other words, updating MongoDB works exactly as described. So, if you have this document in a test colletion:
{ "_id" : "123", "oldfield" : "oldvalue" }
And run the following in the Mongo CLI:
db.test.update({"_id": "123"}, { newfield : "value" })
The new document will look like this:
{"_id": "123", "newfield" : "value"}
If you want to change only some fields, you can use the $ set operator, which sets the value for one or more fields. When you use spring data, you should use the MongoTemplate class to update:
Query q = new Query(Criteria.where("_id").is("123")); Update u = Update .update("newfield", "value") .set("oldfield", "newvalue"); this.template.findAndModify(query, update, Entity.class);
Here you can read about the $ set operator and mongodb update: http://docs.mongodb.org/manual/reference/operators/#_S_set http://docs.mongodb.org/manual/applications/update
source share