3

Code that I want to execute by MongoTemplate:

{
    $merge: {
        into: 'someCollection',
        on: "_id",
        whenMatched: 'merge',
        whenNotMatched: 'discard'
    }
}

I did not find any suitable methods that allow me to describe $merge stage, have doubts if Spring Data MongoDB even supports this stage?

user471011
  • 7,104
  • 17
  • 69
  • 97
  • 1
    Yes it is! https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/aggregation/MergeOperation.html – matthPen Feb 12 '21 at 09:47

1 Answers1

5

Yes, Spring Data MongoDB have support for $merge stage. Your code can be executed by MongoTemplate following way.

MergeOperation mergeOperation = Aggregation.merge()
        .intoCollection("someCollection")
        .on("_id")
        .whenMatched(MergeOperation.WhenDocumentsMatch.mergeDocuments())
        .whenNotMatched(MergeOperation.WhenDocumentsDontMatch.discardDocument())
        .build();

Use this mergeOperation with mongoTemplate.

Harshit
  • 1,334
  • 1
  • 9
  • 23