首页 > 解决方案 > MongoDB .Net - 过滤数组子项中的项目

问题描述

我在 mongo 中有一个带有文档的集合。

{
    _id: "1",
    name: "test1",
    active: true,
    cars: [
       { _id: "2", name: "aaa", active: true },
       { _id: "3", name: "bbb", active: false },
       { _id: "4", name: "ccc", active: true },
},
{
    _id: "2",
    name: "test2",
    active: false,
    cars: [
       { _id: "10", name: "aaa", active: true }
}

我想只返回活动项目。在这个例子中:

{
    _id: "1",
    name: "test1",
    active: true,
    cars: [
       { _id: "2", name: "aaa", active: true },
       { _id: "4", name: "ccc", active: true },
}

我怎么做?

标签: .netmongodb

解决方案


您需要对$filter非活动数组元素使用聚合管道

db.col.aggregate([
    {$match : {"active" : true}},
    {$addFields : {
        cars : {
            $filter : {
                input : "$cars", 
                as : "c", 
                cond : "$$c.active"}
            }
    }}
])

结果

> db.col.aggregate([{$match : {"active" : true}},{$addFields : {cars : {$filter : {input : "$cars", as : "c", cond : "$$c.active"}}}}]).pretty()
{
        "_id" : "1",
        "name" : "test1",
        "active" : true,
        "cars" : [
                {
                        "_id" : "2",
                        "name" : "aaa",
                        "active" : true
                },
                {
                        "_id" : "4",
                        "name" : "ccc",
                        "active" : true
                }
        ]
}

推荐阅读