Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my MongoDB $or query work?

Tags:

mongodb

I'm trying to perform an "$or" search to match of of two regular expressions as follows:

{
    "metadata.text": {
        "$or": [
            {
                "$regex": ".*hello.*"
            },
            {
                "$regex": ".*world.*"
            }
        ]
    }
}

I'm using mlab.com and am receiving the following error:

MongoDB error: "Command failed with error 2: 'unknown operator: $or' on server ZZZZZZZ. The full response is { "ok" : 0.0, "errmsg" : "unknown operator: $or", "code" : 2, "codeName" : "BadValue" }." Please contact [email protected] if you need assistance.

Why is $or detected as an unknown operator?

like image 840
Hoa Avatar asked Dec 28 '17 21:12

Hoa


1 Answers

Simply because $or should be a top level operator in your query, like this:

db.collection.find({
        "$or": [
            {
                "metadata.text": { "$regex": ".*hello.*" }
            },
            {
                "metadata.text": { "$regex": ".*world.*" }
            }
        ]
})
like image 108
mickl Avatar answered Nov 15 '22 07:11

mickl