MongoTemplate 聚合获得不同的值

MongoTemplate aggregate get distinct values

我正在尝试获取不同元素的列表作为我在 MongoTemplate 聚合函数中的最终结果。我在聚合中间收到如下列表,

[
   {
      "_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"
   }
]

如何添加另一个 AggregationOperation 以获得不同的值作为我的最终结果,如下所示?

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

添加两个步骤:

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")
);