MongoDB 根据对象成员过滤对象数组内容 [英] MongoDB filter objects array content based on object member

查看:30
本文介绍了MongoDB 根据对象成员过滤对象数组内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象数组,想知道是否有办法将结果过滤为仅返回 QtyIn 记录或仅返回 QtyOut 记录?任何提示都非常感谢.感谢您的帮助

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")
        }    
    ],
}

推荐答案

您可以在 $filter:

You can compare qTyIn with undefined within $filter:

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

Mongo 游乐场

这篇关于MongoDB 根据对象成员过滤对象数组内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆