Search code examples
mongodbgomongo-go

check field exits,compare int value using go mongodb


I am using golang as backend with mongodb.I want to perform below code

"$match" : bson.M{
        "emp_dept": "xyz",
        "skills":     "asd",
        "emp_del_status": bson.M{"$exists": true, "$eq": 0}, // emp account is active
    }

My Collection is

Collection Employee

{
"emp_dept": "xyz",
"skills":     "fgg",
}
{
"emp_dept": "xyz",
"skills":     "cvv",
}
{
"emp_dept": "xyz",
"skills":     "asd",
"emp_del_status":0,
}

In my DB some of the documents do not contain emp_del_status key. So I want to check If any document contains emp_del_status key then check the value 0 and return result based on other parameter and emp_del_status key both. but if document does not contain emp_del_status key then result will come based on other parameters only. How we can check this?


Solution

  • So basically what you want is an $or for emp_del_status.

    You want documents where "emp_dept": "xyz" and "skills": "asd", and emp_del_status is either 0 or missing (does not exist).

    This is how you can describe that filter:

    "$match": bson.M{
        "emp_dept": "xyz",
        "skills":   "asd",
        "$or": []interface{}{
            bson.M{"emp_del_status": bson.M{"$exists": false}},
            bson.M{"emp_del_status": 0},
        },
    }