SO...
I am trying to write a single query to update and return multiple documents stored in an Atlas MongoDB ReplicaSet. Mongo version 7 and Java Sync Driver version 4.11.1 to build and execute the query.
updateMany is simple and straightforward, but it requires an additional query to retrieve the updated objects.
It seems like I want to use MongoDB's Updates with Aggregation Pipeline but I am having trouble getting it quite right, when I try to use ReplaceRoot with the following code...
final ReplaceRootOperation replaceRootOperation = Aggregation.replaceRoot( ObjectOperators.MergeObjects.merge( current(), new Document(myTimestampField, Instant.now()) ));final AggregationResults<MyDatabaseModel> aggregationResults = mongoTemplate.aggregate( Aggregation.newAggregation(matchOperation, replaceRootOperation), MyDatabaseModel.COLLECTION_NAME, MyDatabaseModel.class );return aggregationResults.getMappedResults();
...this returns the updated documents with the appropriate timestamps, but it doesn't actually update the database and I get the same thing when I try to use $set.
I also tried using a MergeOperation
instead, but I found that it wasn't respecting the matchOperation and instead my results included results that were not a part of the match (but only the matched ones were actually updated). I removed everything except the match to confirm that was working as expected, but for some reason, as soon as I add the merge operation, more documents were being returned. Maybe this is because the merge was using the _id
field whereas the match was using other fields?
How can I update multiple documents and return them in Atlas MongoDB 7?