【问题标题】:MongoDB .Net - Filter items in array childMongoDB .Net - 过滤数组子项中的项目
【发布时间】:2018-12-28 18:38:11
【问题描述】:

我在 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 },
}

我该怎么做?

【问题讨论】:

    标签: .net mongodb


    【解决方案1】:

    您需要使用聚合管道来$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
                    }
            ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2020-07-30
      • 2013-01-16
      • 1970-01-01
      • 2018-04-01
      相关资源
      最近更新 更多