MongoDB: 只获取嵌套数组文档中的特定字段

MongoDB: Get only specific fields in nested array documents

我正在尝试从以下格式的嵌套数组文档中投影值。我期望的是仅显示在查找查询中选择的特定 specTypespecValue

{
    "carId": "345677"
    "car" : {
        "model" : [ 
            {
                "specs" : [ 
                    {
                        "specType": "SEDAN"
                        "specValue" : "1"
                    }, 
                    {
                        "specType": "BR_INC"
                        "specValue" : "yes"
                    }, 
                    {
                        "specType": "PLAN"
                        "specValue" : "gold"
                    }
                ]
            }
        ]
    }
}

This is what I have tried.

db.cars.find({carId:'345677','car.model.specs.specType':'SEDAN'},{'car.model.specs.specValue':1})

这种方法给了我所有的 specValues 而不是像下面这样。

{
    "carId": "345677"
    "car" : {
        "model" : [ 
            {
                "specs" : [ 
                    {
                        "specValue" : "1"
                    }, 
                    {
                        "specValue" : "yes"
                    }, 
                    {
                        "specValue" : "gold"
                    }
                ]
            }
        ]
    }
}

我如何使它正确地进入正确的格式。谁能帮忙。

{
    "carId": "345677"
    "car" : {
        "model" : [ 
            {
                "specs" : [ 
                    {
                        "specType": "SEDAN"
                        "specValue" : "1"
                    }
                ]
            }
        ]
    }
}

您可以使用以下聚合

db.collection.aggregate([
  { "$project": {
    "car": {
      "model": {
        "$filter": {
          "input": {
            "$map": {
              "input": "$car.model",
              "in": {
                "specs": {
                  "$filter": {
                    "input": "$$this.specs",
                    "cond": { "$eq": ["$$this.specType", "SEDAN"] }
                  }
                }
              }
            }
          },
          "cond": { "$ne": ["$$this.specs", []] }
        }
      }
    }
  }}
])