Query documents, update it and return it back to MongoDB

In my MongoDB 3.2 based application I want to perform the documents processing. In order to avoid the repeated processing on the same document I want to update its flag and update this document in the database.

The possible approach is:

  • Query the data: FindIterable<Document> documents = db.collection.find(query); .
  • Perform some business logic on these documents.
  • Iterate over the documents , update each document and store it in a new collection.
  • Push the new collection to the database with db.collection.updateMany(); .
  • Theoretically, this approach should work but I'm not sure that it is the optimal scenario.

    My question:
    Is there any way in MongoDB Java API to perform the followings two operations:

  • to query documents (to get them from the DB and to pass to the separate method);
  • to update them and then store the updated version in DB;
  • in more elegant way comparing to the proposed above approach?


    You can update document inplace using update:

    db.collection.update(
        {query},
        {update},
        {multi:true}
    );
    

    It will iterate over all documents in the collection which match the query and updated fields specified in the update .

    EDIT:

    To apply some business logic to individual documents you can iterate over matching documents as following:

    db.collection.find({query}).forEach(
        function (doc) {
            // your logic business
            if (doc.question == "Great Question of Life") {
                doc.answer = 42;
            }
            db.collection.save(doc);
        }
    )
    
    链接地址: http://www.djcxy.com/p/61956.html

    上一篇: 如果MongoDB适用于同一文档,它们是否是批量更新的原子?

    下一篇: 查询文档,更新它并将其返回给MongoDB