首页 > 解决方案 > Mongodb 使用带有嵌套数组的 $filter

问题描述

我有这个文件

[

    {
        "id" : 1,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 12
                    }
                ]
            },
            {
                "value": 100,
                "term": [
                    {
                        "term_value" : 18
                    }
                ]
            }
        ]
    },
    {
        "id" : 2,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 18
                    }
                ]
            },
            {
                "value": 150,
                "term": [
                    {
                        "term_value" : 24
                    }
                ]
            }
        ]
    }
]

我想使用聚合框架来获取至少有一个prices.term.value等于的文档6

我正在使用这个

Product.aggregate(
    [
        { "$match": { "prices.term.value": {"$eq": 6} } },
    ]
)

它返回所有文档,因为所有文档都至少有一个术语满足条件,没有问题

我需要的是,使用 $filter 只返回至少有一个条件满足条件的价格

这是我需要的虚拟代码

{
    "$addFields": {
        "prices": {
            "$filter": {
                "input": "$prices",
                "as": "field0",
                "cond": {
                    "$eq": [
                        "$$field0.term.term_value",
                        6
                    ]
                }
            }
        }
    }
}

但它也不工作,有什么建议吗?

我需要的结果是

[

    {
        "id" : 1,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 12
                    }
                ]
            },
        ]
    },
    {
        "id" : 2,
        "prices" : [
            {
                "value": 50,
                "term": [
                    {
                        "term_value" : 6
                    },
                    {
                        "term_value" : 18
                    }
                ]
            },
        ]
    }
]

谢谢

标签: mongodbmongooseaggregation-framework

解决方案


推荐阅读