mongodb过滤数组内的数组

时间:2017-12-21 12:55:26

标签: mongodb nosql mongodb-query aggregation-framework

在我的mongodb文档中,我在数组和数组中有数组。我想在投影中对其进行过滤。

示例文档:

{
    "_id" : ObjectId("5a3ba402cc96937e91e2861d"),
    "id" : 1,
    "name" : "a",
    "var" : [ 
        {
            "id" : 11,
            "name" : "aa",
            "data" : [ 
                {
                    "type" : 1,
                    "value" : "A"
                }, 
                {
                    "type" : 2,
                    "value" : "B"
                }
            ]
        }, 
        {
            "id" : 12,
            "name" : "ab",
            "data" : [ 
                {
                    "type" : 26,
                    "value" : "Z"
                }, 
                {
                    "type" : 10,
                    "value" : "J"
                }
            ]
        }
    ]
}

当我运行以下查询时,

db.harshit.aggregate([{
    $match: { "id" : 1}
}, {
    $project: {
        "_id" : 1,
        "id" : 1,
        "name" : 1,
        "var" : {
            $filter: {
                input: "$var",
                as: "var1",
                cond: {
                    "$eq": ["$$var1.id", 12]
                }
            }
        }
    }
}
])

然后它给出了预期的结果

{
    "_id" : ObjectId("5a3ba402cc96937e91e2861d"),
    "id" : 1,
    "name" : "a"
    "var" : [ 
        {
            "id" : 12,
            "name" : "ab",
            "data" : [ 
                {
                    "type" : 26,
                    "value" : "Z"
                }, 
                {
                    "type" : 10,
                    "value" : "J"
                }
            ]
        }
    ]
}

但如果我使用以下查询

db.harshit.aggregate([{
    $match: { "id" : 1}
}, {
    $project: {
        "_id" : 1,
        "id" : 1,
        "name" : 1,
        "var" : {
            $filter: {
                input: "$var",
                as: "var1",
                cond: {
                    "$eq": ["$$var1.data.type", 26]
                }
            }
        }
    }
}
])

然后它为" var"

提供空数组
{
    "_id" : ObjectId("5a3ba402cc96937e91e2861d"),
    "id" : 1,
    "name" : "a"
    "var" : []
}

我想把过滤器放在嵌套数组" var.data"并希望投影符合条件的对象。

如何过滤那些嵌套数组?

0 个答案:

没有答案