过滤出嵌套数组 Mongo DB 聚合中的记录

问题描述 投票:0回答:1

我正在尝试从 Mongo Collection 的内部数组中过滤我们的记录。下面给出了示例:

{
 "cId":23456,
 "description":"car",
  "brand": [{
    "bId":23,
    "bName":"toyota",
     "model":[{
      "mName":"camry",
      "vId":"12"
      },
      {
      "mName":"corolla",
      "vId":"13"
      }]
   },{
    "bId":24,
    "bName":"honda",
     "model":[{
      "mName":"accord",
      "vId":"14"
      },
      {
      "mName":"civic",
      "vId":"15"
      }]
   }]
  }

我想从内部模型数组中过滤掉记录,就像输入“civic”一样,我的输出应该如下所示:

{
 "cId":23456,
 "description":"car",
  "brand": [{
    "bId":24,
    "bName":"honda",
     "model":[
      {
      "mName":"civic",
      "vId":"15"
      }]
   }]
  }

我尝试多次展开来展开内部数组,但无法分组回所需的格式作为其内部数组。

mongodb mongodb-query aggregation-framework
1个回答
0
投票

也许是这样的:

db.collection.aggregate([
{
 $match: {
   "brand.model.mName": "civic"
 }
},
{
"$addFields": {
  "brand": {
    "$filter": {
      "input": {
        "$map": {
          "input": "$brand",
          "as": "b",
          "in": {
            "$mergeObjects": [
              "$$b",
              {
                "model": {
                  "$filter": {
                    "input": "$$b.model",
                    "as": "m",
                    "cond": {
                      "$eq": [
                        "$$m.mName",
                        "civic"
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      },
      "as": "fb",
      "cond": {
        "$ne": [
          "$$fb.model",
          []
          ]
        }
       }
     }
    }
   }
])

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.