I'm running a MongoDB aggregation where the last stage is a $merge
that writes some field to another collection. Basically, this $merge should make an effect only on a single document (this is why we have on: "_id"
.
Here's how I do it with Java:
var merge = Aggregation.merge().intoCollection("items")
.on("_id")
.whenMatched(MergeOperation.WhenDocumentsMatch.mergeDocuments())
.whenNotMatched(MergeOperation.WhenDocumentsDontMatch.discardDocument())
.build();
var agg = Aggregation.newAggregation(match, group, merge);
var aggResult = mongoTemplate.aggregate(agg, "prices", Item.class);
The aggregation does what it needs and I can see that the requested document has changed, but the problem is that aggregate()
returns all the documents in the collection.
This is a major drawback and can't scale well when the collection is large enough.
How can I change my query so it will return only the changed document. Or if not possible, just apply the query without returning anything.