Home > Software design >  $and operation syntax
$and operation syntax

Time:11-18

I should take a data with condition:

(Founded in 2004 OR Founded in October) AND (social OR web)

I used to try like this:

db.companies.find({
            $or: [
                {"founded_year": 2004}, 
                {"founded_month": 10}
            ], 
            $or: [
                {"category_code": "web"}, 
                {"category_code": "social"}
            ]
        }).count()

but this goes wrong. The corrent answer is:

db.companies.find({ "$and": [
                        { "$or": [ { "founded_year": 2004 },
                                   { "founded_month": 10 } ] },
                        { "$or": [ { "category_code": "web" },
                                   { "category_code": "social" }]}]}).count()

Why should i use $and operator in the inner {}? I thought i didn't have to write this operator and i can just list the conditions in {} with comma, because in MongoDB university course there where this expression: enter image description hereenter image description here

CodePudding user response:

In the query

{
    "$or": [
        {"founded_year": 2004},
        {"founded_month": 10}
    ],
    "$or": [
        {"category_code": "web"},
        {"category_code": "social"}
    ]
}

you have two keys named $or. Or a mongo query follows the JSON notation. And in JSON format, only the last key with the duplicate name is going to be used.

Using the $and will fix this issue. Because $and is a list, you will not have anymore an object containing the two same keys

  • Related