问题描述
我尝试使用嵌套运算符(OR/AND/...)创建一个MongoDB查询过滤器.但是lib需要创建一个 bson.D
并将其传递到 bson.E
元素中.如果我需要在 AND/OR
内包含 OR/AND
-我需要将 bson.M + bson.D
放入 bson.D
像这样:
I try to create a MongoDB query filter with the nested operators (OR/AND/...). But lib requires to create a bson.D
and pass bson.E
elements into it. If I need to have OR/AND
inside AND/OR
- I need to put bson.M + bson.D
inside bson.D
like this:
filter := bson.M{"$and": bson.D{{"p", 10}, bson.M{"$or": bson.D{{"s", 30}, {"a", 1}}}}}
..当然是行不通的:不能使用primitive.M文字(类型primitive.M)作为切片文字中的primitive.E类型
.如果稍后我尝试在 bson.D
.. and of course it doesn't work: cannot use primitive.M literal (type primitive.M) as type primitive.E in slice literal
. Probably the same problem will happen if later I try to use a ... in []
logics inside a bson.D
如何在Go和MongoDB官方驱动程序中创建此类嵌套查询?
How do I create such nested queries in Go and official MongoDB driver?
推荐答案
重要的是 $ or
需要一个数组,该数组为 bson.A
.另外, $ and
是默认设置,您无需指明.
What matters is that $or
requires an array, which is bson.A
. Also $and
is the default, you don't have to indicate that.
您的过滤器可以这样定义:
Your filter can be defined like this:
filter := bson.D{
{"p", 10},
{"$or", bson.A{
bson.D{{"s", 30}},
bson.D{{"a", 10}},
}},
}
您也可以使用此:
filter = bson.D{
{"p", 10},
{"$or", bson.A{
bson.M{"s": 30},
bson.M{"a": 10},
}},
}
或者这个:
filter := bson.M{
"p": 10,
"$or": bson.A{
bson.M{"s": 30},
bson.M{"a": 10},
},
}
这篇关于mongo-go-driver:嵌套的OR/AND查询过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!