Ertai87
Ertai87

Reputation: 1316

Updating a MongoDB collection with Java Spring Repositories

I'm having a bit of a problem working with Java Spring Repositories (these ones). I have a collection that has a custom ID field (because there is a constraint in my application that prevents me from using MongoDB ObjectIDs) along with some data. It seems that the save() method built into the CrudRepository interface will only do an update on the database object if you save using the ObjectID, otherwise it will add a new instance of the object. Since I am using a custom ID field, this seems to mean that I have to first delete the old object (if it exists) and then insert a brand new object with the updated fields. Obviously this is very slow (I have to do 3 database calls: one to see if the object exists, one to delete it, and one to insert it, as opposed to 1), so I would like to make sure:

Is there a way to use Java Spring repositories to do updates on collections without using the ObjectID of the object? Thanks.

Upvotes: 0

Views: 6046

Answers (1)

vine
vine

Reputation: 886

You can use the MongoOperations api,

http://docs.spring.io/spring-data/data-mongo/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#findAndModify-org.springframework.data.mongodb.core.query.Query-org.springframework.data.mongodb.core.query.Update-java.lang.Class-

Just autowire the mongoOperation in the custom mongo dao implementation, and you can use this code

mongoOperation.findAndModify(Query query, Update update,Class<T> entityClass)

The query contains the criteria, the update contains the changes you want to apply and entityClass pertains to the mongo document.

You can also follow other similar operations in this tutorial

http://www.mkyong.com/mongodb/spring-data-mongodb-update-document/

Upvotes: 1

Related Questions