Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Spring Data Mongo update only dirty field in a document?

I've started using spring-data-mongo for an application where there are a lot of stuff to be persisted.

We actually chose mongo because it's advertised so. Now heavily addicted to spring we found our life very easy using some of it's features (kudos for the hard work spring data folks).

But there is one thing: a document with over 60 fields. So my question about speed and scalability is that can spring-data-mongo only update the dirty fields in the mongo database just like Hibernate does it? a little like how it was explained here by Arthur Ronald F D Garcia

thanks for reading this

like image 704
black sensei Avatar asked Nov 15 '12 12:11

black sensei


1 Answers

From MongoDB documentation:

If the update argument contains only field and value pairs, the update() method replaces the existing document with the document in the update argument, except for the _id field.

In other words, MongoDB's update works exactly like you described. So if you have this document in test colletion:

{ "_id" : "123", "oldfield" : "oldvalue" }

And run the following in mongo CLI:

db.test.update({"_id": "123"}, { newfield : "value" })

The new document will look like this:

{"_id": "123", "newfield" : "value"}

If you want to modify just some fields, you could use the $set operator that will set a value for one or more fields. As you are using spring data, you should use MongoTemplate class to make this updates:

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);

You could read about $set operator and mongodb update here: http://docs.mongodb.org/manual/reference/operators/#_S_set http://docs.mongodb.org/manual/applications/update

like image 101
Miguel Cartagena Avatar answered Oct 02 '22 09:10

Miguel Cartagena