【问题标题】:mongodb query using $or and $elemMatch使用 $or 和 $elemMatch 的 mongodb 查询
【发布时间】:2015-10-28 20:23:08
【问题描述】:

我有以下 2 个文档,如果任何文档在图像数组中具有 4x4 或 3x3,我需要在其中搜索。

{
    "images" : [ 
        {
            "4x4" : {
                "path" : "4-1.jpg"
            },
            "2x2" : {
                "path" : "2-1.jpg"
            }
        }
    ]
}
{
        "images" : [ 
        {
            "3x3" : {
                "path" : "3-1.jpg"
            }
        }
    ]
}

我有以下 mongodb 查询。但似乎无法找到一起使用 $or 和 $elemMatch 的方法。

db.getCollection('images').find({
    "images" : {
        $elemMatch : {
            "4x4" : {$exists :  true}
        }
    }
    })

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    你当然可以这样写:

    db.images.find({
        "images": {
            "$elemMatch": {
                "$or": [
                    { "4x4": { "$exists": true } },
                    { "3x3": { "$exists": true } }
                ]
            }
        }
    })
    

    但你不必这样做,你基本上可以这样写:

    db.images.find({
        "$or": [
            { "images.4x4": { "$exists": true } },
            { "images.3x3": { "$exists": true } }
        ]
    })
    

    $elemMatch 运算符通常仅在您需要多个条件来匹配数组“元素”时才需要。一般数组检查或单个属性匹配最好用"dot notation" 表示。

    【讨论】:

    • +1 >> $elemMatch 运算符通常仅在您需要多个条件来匹配数组“元素”时才需要。一般数组检查或单个属性匹配最好用“点符号”表示。同一问题的 2 个答案的另一个 +1。谢谢!
    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多