Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Data MongoDB Update all document fields

I'm migrating from SQL (JPA) to MongoDB, and I heard great things about Spring-Data, so I'm using it, especially for the whole conversion between DBObjects and application objects.

Most of my requirements are met, but I don't know how to migrate JPA's update functionality to Spring-Data with MongoDB: 1. save/update is implicit, handled by hibernate 2. update updates all values according to the given object

Similarly to JPA, when using com.mongodb.DB you can perform a one-line "Update" operation:

public boolean update(String collectionName, DBObject referenceObject, DBObject object) {
    WriteResult result = this.db.getCollection(collectionName).update(referenceObject, object);
    return parseWriteResult(result);
}

It saves/updates the object that equals the reference object according to the values in the given object, and depending on whether the object is in the DB or not.

Now that I'm using MongoOperations I can only update the object using the "Update" object, where I have to seed the values one at a time:

MongoOperations client = ...

...

Update update = new Update();
update.set("past", 1);
update.set("current", 3);

...

client.updateFirst(query, update, clazz);

Is there any way to use the functionality like in JPA?

like image 938
Ido Cohn Avatar asked Jul 07 '26 22:07

Ido Cohn


1 Answers

I am not sure that I 100% understand your question but it seems that you trying to migrate your data from a SQL database using Hibernate into MongoDB using Spring-Data.

We recently migrated all of the binary data in our application from Apache Jackrabbit into MongoDB also with Spring-Data. In addition there was one instance where we were still storing some binary data in our SQL database which was also migrated:

We migrated this data in the following manner:

  • Retrieve all the entities required from hibernate.
  • Create a new instance of your MongoDB document.
  • Loop through all of these entities copying the data from hibernate entities onto the MongoDB document.
  • Call MongoOperations#save() for each document.

You also mentioned something about updating:

To update a particular document just use MongoOperations#updateFirst().

Alternatively you could use MongoOperatons#findOne() too look up the object you want, then update the fields you want and then call MongoOperations#save() which if you read the javadoc you will see performs an upsert.

like image 174
Trevor Gowing Avatar answered Jul 09 '26 11:07

Trevor Gowing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!