简体   繁体   English

使用Java在MongoDB中收集集合。

[英]Upsert of collection in MongoDB, using Java.

  1. I am using a MongoDb to store a collection 我正在使用MongoDb来存储集合
  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. 我想将整个内存集合发送到DB,并且我需要“一些魔术”,它将仅更新内存中已更改的集合的那些数据。

Can anybody help me with this "some magic" that I am looking for? 有人可以帮我解决我正在寻找的“某种魔术”吗?

I am using Java, Heroku, mLab:MongoDB tech stack. 我正在使用Java,Heroku,mLab:MongoDB技术堆栈。

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. 假设in memory数据库是一个集合,每个文档都有的ID,你可以使用insertAll的方法MongoTemplate倾倒整个集合。 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: upsert而言,您可以创建Query并使用MongoTemplate upsert方法,例如:

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. 这是insertAllupsert方法的javadoc。

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. 如果你正在使用的核心蒙戈- Java的应用程序,那么你可以看看这个这个 SO答案做同样的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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