【问题标题】:MongoTemplate aggregate get distinct valuesMongoTemplate 聚合获得不同的值
【发布时间】:2020-06-13 21:58:40
【问题描述】:

我试图在 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"
   }
]

【问题讨论】:

  • _id分组。

标签: mongodb mongodb-query aggregation-framework mongotemplate


【解决方案1】:

添加两步:

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

MongoPlayground

春蒙哥

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

【讨论】:

  • 难道没有一个步骤我们可以做到这一点,而不是按属性分组,然后用值替换根属性吗? :)
  • @Sandeepa 要找到不同的值,我们需要对它们进行分组 :) 如果data 字段中的输出数据对您来说没问题,您可以跳过 replaceRoot
猜你喜欢
  • 2023-03-20
  • 2016-04-08
  • 2023-02-13
  • 2019-07-28
  • 2020-09-28
  • 2015-01-08
  • 2021-08-03
  • 1970-01-01
  • 2021-06-14
相关资源
最近更新 更多