【问题标题】:Filter array element which does not have a specific field in MondoDB aggregation过滤 MongoDB 聚合中没有特定字段的数组元素
【发布时间】:2019-11-13 23:09:54
【问题描述】:

我在 mongodb 中有一个 people 集合,如下所示。

MongoDB 版本:4.0.13

{
    "_id" : ObjectId("5dcbeb97e184e0f527c6a3e7"),
    "name" : "nithin",
    "age" : 35.0,
    "addresses" : [ 
        {
            "street" : "xyz",
            "city" : "Tvm"
        }, 
        {
            "street" : "pqr",
            "city" : "KLM"
        }, 
        {
            "street" : "abc"
        }
    ]
}


{
    "_id" : ObjectId("5dcbebe4e184e0f527c6a3e8"),
    "name" : "akash",
    "age" : 21.0,
    "addresses" : [ 
        {
            "street" : "lon",
            "city" : "London"
        }, 
        {
            "street" : "par",
            "city" : "paris"
        }, 
        {
            "street" : "abc"
        }
    ]
}

我需要过滤掉所有没有city 属性的地址。我目前取得的成就是这样的

db.getCollection('People').aggregate([

    {
        $project:
        {
            "name":1,
            "age":1,
            "addresses":
            {
                $filter:
                {
                    input:"$addresses",
                    as:"address",
                    cond:{$not:["$$address.city"]}
                }
            }

        }   


    }

])

结果:我得到的所有地址都没有city 属性(这与我需要的完全相反)。我找不到任何帮助。如何否定not 结果

我也试过了

        $filter:
        {
            input:"$addresses",
            as:"address",
            cond:{"$exists":["$$address.city":true]}
        }

结果:

错误:第 14 行:意外令牌:

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

在这种情况下没有必要进行聚合。您可以将 find 与 $elemMatch 运算符一起使用:

db.people.find({
    addresses: {$elemMatch : {city: {$exists: false}}}
})

但是如果你想使用聚合,那么你可以在同一个查询上做匹配:

db.people.aggregate([
    {$match: {addresses: {$elemMatch : {city: {$exists: false}}}}}
])

您也可以如下所示进行操作,但我认为 elemMatch 会更快:

db.people.aggregate([
{$unwind: '$addresses'},
{$match: {"addresses.city" : {$exists: false}}}
{$group: { _id : '$_id', addresses: {$addToSet: "$addresses"}}}
])

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2016-10-07
    • 2020-10-16
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多