使用$或和$ elemMatch进行mongodb查询

Fai*_*eef 1 mongodb mongodb-query

我有以下2个文件,我需要搜索是否有任何文件在图像阵列中有4x4或3x3.

{
    "images" : [ 
        {
            "4x4" : {
                "path" : "4-1.jpg"
            },
            "2x2" : {
                "path" : "2-1.jpg"
            }
        }
    ]
}
{
        "images" : [ 
        {
            "3x3" : {
                "path" : "3-1.jpg"
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我有以下mongodb查询.但似乎无法一起使用$或$ elemMatch.

db.getCollection('images').find({
    "images" : {
        $elemMatch : {
            "4x4" : {$exists :  true}
        }
    }
    })
Run Code Online (Sandbox Code Playgroud)

Bla*_*ven 6

那么你当然可以这样写:

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

但你没有必要,因为你基本上可以像这样写:

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

$elemMatch操作者,当你需要多个条件以匹配的数组"元素"通常才是必需的.一般数组检查或单一属性匹配用"点符号"更好地表示.