为了账号安全,请及时绑定邮箱和手机立即绑定

$or 内 $and 在 $filter 条件下不起作用

$or 内 $and 在 $filter 条件下不起作用

Go
沧海一幻觉 2022-06-27 15:08:02
我正在将 golang 与 mongodb、mgo 集合一起使用我的 mongodb 集合是 **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    }    ..........下面是我使用管道的 Go 代码    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,                        },                    },                },            }},        })此代码返回错误Unrecognized expression '$$element.status'我们如何使用mgo 集合在 golang中使用$orinside ?$and当我对or语句发表评论时,它返回结果,但是当我使用它时,or它给出了错误。任何人都可以建议我如何在 $ 和管道中使用 $ 或
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

 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}}, 

            }

    } 

我尝试使用此代码编写 conditionParam,它对我有用。我还没有检查所有案例,但我想知道你的建议,编写or运算符来检查字段是否存在以及是否存在检查其值是否正确。


查看完整回答
反对 回复 2022-06-27
  • 1 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号