从mongo聚合函数中获取文档ID和默认值

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

这是我的示例文档结构{

    id: "abc"
    config: [
        {
            feature_id: f1,
            properties: [
                {
                    id: 1
                    todo: "check the microwave"
                }
                {
                    id: 2
                    todo: "check the food"
                }
            ]
        },
        {
            feature_id: f2,
        }
    ]
}

我正在使用mongoDb聚合函数来获取基于todofeature_id。试过多个解决方案,但似乎失败了

db.getCollection('foo').aggregate([

    {$match: {
                "id": "abc",
                "config": {
                        $elemMatch: {
                            "feature_id": "f1"
                        }
                }
            }
    },
    {   
        $project : { "config": 1, "_id": 0}
    },
    {
        $unwind: "$configurations"
    },
]);

虽然我得到了结果,但它远非令人满意。

预期的产出

[{id: 1 , todo: "check the microwave" }]
mongodb aggregation-framework
2个回答
1
投票

您可以使用3.4中的任何以下聚合查询。

 db.getCollection('foo').aggregate([
  {"$match":{"id":"abc","config.feature_id":"f1"}},
  {"$unwind":"$config"},
  {"$match":{"config.feature_id":"f1"}},
  {"$unwind":"$config.properties"},
  {"$match":{"config.properties.id":1}},
  {"$project":{"data":"$config.properties"}},
  {"$replaceRoot":{"newRoot":"$data"}}
])

要么

db.getCollection('foo').aggregate([
  {"$match":{"id":"abc","config.feature_id":"f1"}},
  {"$project":{
    "property":{
      "$arrayElemAt":[
        {"$filter":{
          "input":{
            "$let":{
              "vars":{
                "config":{
                  "$arrayElemAt":[
                    {"$filter":{
                        "input":"$config",
                        "as":"cf",
                        "cond":{"$eq":["$$cf.feature_id","f1"]}
                    }},
                   0
                  ]
                }
              },
              "in":"$$config.properties"
            }
          },
          "as":"pf",
          "cond":{"$eq":["$$pf.id",1]}
        }},0]}
  }},
  {"$replaceRoot":{"newRoot":"$property"}}
])

0
投票

这是另一种解决方案

db.getCollection('foo').aggregate([
    {"$match":{"id":"abc","config.feature_id":"f1"}},
    {"$unwind":"$config"},
    {"$match":{"config.feature_id":"f1"}},
    {"$unwind":"$config.properties"},
    {"$match":{"config.properties.id":1}},
    {"$project":{"_id": "$config.properties.id", "todo": "$config.properties.todo"}},
])
© www.soinside.com 2019 - 2024. All rights reserved.