kaun jovi
kaun jovi

Reputation: 615

Upsert of collection in MongoDB, using Java.

  1. I am using a MongoDb to store a collection
  2. The first time around the collection is inserted without any other consideration
  3. Once the data has been initialized in DataBase, the rest of the application makes changes in the collection in memory - not in DataBase.
  4. Under certain conditions I want to "upsert" the memory collection in DataBase.
  5. I want to send the whole memory collection to DB and I need "some magic" that will update only those data of the collection that have changed in memory.

Can anybody help me with this "some magic" that I am looking for?

I am using Java, Heroku, mLab:MongoDB tech stack.

Upvotes: 0

Views: 2153

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30849

Assuming the in memory database is a collection and each document has the id, you can use insertAll method of MongoTemplate to dump the whole collection. It will keep the unchanged documents as is and update the others.

As far as upsert is concerned, you can create a Query and use upsert method of MongoTemplate, e.g.:

Query query = new Query(Criteria.where("_id").is(my_id));
mongoTemplate.upsert(query, document, Document.class, "collection_name");

Here's the javadoc of insertAll and upsert methods.

Update

If you are using core mongo-java-driver then you can have a look at this and this SO answers to do the same operations.

Upvotes: 1

Related Questions