$or inside $and in $filter condition not working

154 views Asked by At

I am using golang with mongodb,mgo collection

My mongodb collection is

 **department**
    {
     dept_id:1,
     dept_name:'CSE',
     dept_overview:'overview'
    }
   ................

**employee**
    {
    emp_id:1,
    emp_name:'abc',
    qualification:'PHD',
    emp_dept:'CSE',
    city:'xyz'
    }
    {
    emp_id:2,
    emp_name:'xyz',
    qualification:'PHD',
    emp_dept:'CSE',
    city:'xyz',
    status:1
    }
    ..........

Below is my Go code using pipeline

    var conditionParam []bson.M
    if(city!=""){
        conditionParam = []bson.M{
        bson.M{"$eq": []string{"$$element.qualification", "PHD"}},
            bson.M{"$eq": []string{"$$element.emp_dept", "CSE"}},
                bson.M{"$eq": []string{"$$element.city", "xyz"}},
                bson.M{"$or": []bson.M{
            bson.M{"$$element.status": bson.M{"$exists": false}},
            bson.M{"$$element.status": 1}}, 
                },
            }
    }else if(){
    --------------------
}

matchStage:=bson.M{"$match":bson.M{'dept_id':1}}
lookupStage:=bson.M{"$lookup": bson.M{
    "from":         "employee",
    "localField":   "dept_name",
    "foreignField": "emp_dept",
    "as":           "result_list",
}}
    pipeline := getCollection.Pipe([]bson.M{
            matchStage,
            lookupStage,
            {"$addFields": bson.M{
                "result_list": bson.M{
                    "$filter": bson.M{
                        "input": "$result_list",
                        "as":    "element",
                        "cond": bson.M{
                            "$and": conditionParam,
                        },
                    },
                },
            }},
        })

This code return error

Unrecognized expression '$$element.status'

How We can use $or inside $and in golang using mgo collection?

when I put comment on or statement it returns the result but when I used the or it gives error.Can anyone suggest me how to use $or inside $and in pipeline

1

There are 1 answers

0
Rajandeep Kaur On BEST ANSWER
 var conditionParam []bson.M
        if city == "" {
            conditionParam = []bson.M{
                bson.M{"$eq": []string{"$$element.qualification", "PHD"}},
                bson.M{"$eq": []string{"$$element.emp_dept", "CSE"}},
                bson.M{"$eq": []string{"$$element.city", "xyz"}},
                bson.M{"$or": []interface{}{"$exists", []interface{}{"$$element.status", false}}},
                bson.M{"$or": []interface{}{"$$element.status", 1}}, 
            }
    } 

I tried this code to write conditionParam and It worked for me. I did not check all the cases yet but I want to know yours suggesstion, Is it right way to write the or operator to check field exists and if exists check its value.