Sandeepa
Sandeepa

Reputation: 3755

MongoTemplate aggregate get distinct values

I'm trying to get a list of distinct elements as my final result in a MongoTemplate aggregate function. And I'm receiving a list like below at the middle of the aggregate,

[
   {
      "_id":"333",
      "name":"cat Three name",
      "description":"cat item description"
   },
   {
      "_id":"222",
      "name":"cat Two name",
      "description":"cat item description"
   },
   {
      "_id":"222",
      "name":"cat Two name",
      "description":"cat item description"
   },
   {
      "_id":"333",
      "name":"cat Three name",
      "description":"cat item description"
   }
]

How can I add another AggregationOperation to get distinct values as my final result like below?

[
   {
      "_id":"222",
      "name":"cat Two name",
      "description":"cat item description"
   },
   {
      "_id":"333",
      "name":"cat Three name",
      "description":"cat item description"
   }
]

Upvotes: 1

Views: 1094

Answers (1)

Valijon
Valijon

Reputation: 13103

Add two steps:

db.collection.aggregate([
  {
    $group: {
      _id: "$_id",
      data: {
        $first: "$$ROOT"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  }
])

MongoPlayground

Spring-mongo

Aggregation agg = newAggregation(
    ... // Your pipeline
    group("_id").first("$$ROOT").as("data"),
    replaceRoot("data")
);

Upvotes: 3

Related Questions