MongoDB filter objects array content based on object member

自闭症网瘾萝莉.ら 提交于 2021-02-05 08:15:27

问题


I have the following objects array and was wondering if there is a way to filter results as return only QtyIn records or return only QtyOut records? Any hint is highly appreciated. Thanks for your help

{
    warehouseID: "1234",
    transactions : [ 
        {
            "qtyIn" : "10",
            "transDateTime" : ISODate("2019-09-10T18:54:41.983Z")
        }, 
        {
            "qtyOut" : "11",
            "transDateTime" : ISODate("2019-08-10T18:54:41.983Z")
        },
        {
            "qtyOut" : "200",
            "transDateTime" : ISODate("2019-02-10T11:54:41.983Z")
        }    
    ],
}

回答1:


You can compare qTyIn with undefined within $filter:

db.collection.aggregate([
    {
        $addFields: {
            transactions: {
                $filter: {
                    input: "$transactions",
                    cond: {
                        $ne: [ "$$this.qtyIn", null ]
                    }
                }
            }
        }
    }
])

Mongo Playground



来源:https://stackoverflow.com/questions/61533627/mongodb-filter-objects-array-content-based-on-object-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!