![](/img/trans.png)
[英]How to filter array (of objects) inside one document in mongo db based on some condition
[英]$or inside $and in $filter condition not working
我正在使用 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
它給出錯誤。誰能建議我如何使用 $or inside $and in 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": []interface{}{"$exists", []interface{}{"$$element.status", false}}},
bson.M{"$or": []interface{}{"$$element.status", 1}},
}
}
我試過這段代碼來編寫 conditionParam 並且它對我有用。 我還沒有檢查所有情況,但我想知道您的建議,編寫or
運算符來檢查字段是否存在是否正確,如果存在則檢查其值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.