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:
FindIterable<Document> documents = db.collection.find(query);
. documents
, update each document and store it in a new collection. 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:
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