0

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.

Ertai87
  • 1,156
  • 1
  • 15
  • 26

1 Answers1

1

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/

vine
  • 846
  • 6
  • 10
  • Thanks for the answer! The problem is that there is another feature of MongoRepository that I want to exploit in my application which MongoOperations (and MongoTemplate) do not seem to allow, so I need to use MongoRepository. I do understand that this is relatively trivial using other approaches though. – Ertai87 Oct 14 '15 at 02:56
  • can you please elaborate? – vine Oct 14 '15 at 23:30
  • Actually using mongoOperation doesn't prohibit you to continue using MongoRepository. In fact, MongoRepository uses internally mongoOperations. So for more controlled operations, Spring Data intentionally designed to expose MongoOperations to use it in custom dao impl pattern. Follow this related discussion here, http://stackoverflow.com/questions/17035419/spring-data-mongodb-custom-implementation-propertyreferenceexception Take note, the sample uses MongoTemplate which is also the same as MongoOperation, since MongoTemplate is a subclass of MongoOperation – vine Oct 17 '15 at 00:56