简体   繁体   中英

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.

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 , eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM