mongodb 如何分组数据并返回其余字段?

enyaitl3  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(217)

我想过滤report字段,其中m_name = "ABC",并将其分组。下面是我的示例数据:

{
    "_id" : ObjectId("63f82b8619e8f81b7009d2c3"),
    "type" : "test"
    "created_at" : date
    "created_by" : "admin",
    "report" : [
        {
            "name" : "Day 3",
            "date" : date
            "m_name" : "ABC",
            "created_by" : "admin",
            "created_at" :date
        },
        {
            "name" : "Day 2",
            "date" :date,
            "created_by" : "admin",
            "m_name" : "ABC",
            "created_at" : date
        },
        {
            "name" : "test",
            "date" : date
            "m_name": "123"
            "created_by" : "admin",
            "created_at" : date,
        },
    ],
   ... 20 fields

}

这是我的管道:

.aggregate([ 
       {
          $unwind: "report",
        },
        {
          $match: {
            "report.m_name": "ABC",
          },
        },
        {
          $group: {
            _id: "$_id",
            report: {
              $push: "$report",
            },
            
          },
        },
       ])

如果这样做,输出只有_idreport,如何返回所有其余字段?我已经尝试了$$ROOT,但它嵌入在一个对象中,我希望输出如下:

{
    "_id" : ObjectId("63f82b8619e8f81b7009d2c3"),
    "type" : "test"
    "created_at" : date
    "created_by" : "admin",
    "report" : [
        {
            "name" : "Day 3",
            "date" : date
            "m_name" : "ABC",
            "created_by" : "admin",
            "created_at" :date
        },
        {
            "name" : "Day 2",
            "date" :date,
            "created_by" : "admin",
            "m_name" : "ABC",
            "created_at" : date
        },
    ],
   ... 20 fields

}

我知道project(类型:{$first:“$type”},)就可以了,但是有20个字段,还有其他更简单的方法吗?

bgtovc5b

bgtovc5b1#

使用$filter

db.collection.aggregate([
  {$set: {
      report: {
        $filter: {
          input: "$report",
          cond: {$eq: ["$$this.m_name", "ABC"]}
        }
      }
    }
  }
])

了解它在playground example上的工作原理

相关问题