gpt4 book ai didi

mongodb - $或$内的$和$ filter条件不起作用

转载 作者:行者123 更新时间:2023-12-01 21:12:24 25 4
gpt4 key购买 nike

我将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中的 $or中使用 $and
当我在 or语句上发表评论时,它返回结果,但是当我使用 or时,它给出了错误。有人可以建议我如何在$ and中使用$ or

最佳答案

 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运算符以检查字段是否存在以及是否存在检查其值的正确方法。

关于mongodb - $或$内的$和$ filter条件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63629190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com