[英]mongo-go-driver: nested OR/AND query filter
I try to create a MongoDB query filter with the nested operators (OR/AND/...).我尝试使用嵌套运算符 (OR/AND/...) 创建 MongoDB 查询过滤器。 But lib requires to create a
bson.D
and pass bson.E
elements into it.但是 lib 需要创建一个
bson.D
并将bson.E
元素传递给它。 If I need to have OR/AND
inside AND/OR
- I need to put bson.M + bson.D
inside bson.D
like this:如果我需要在
AND/OR
使用OR/AND
- 我需要像这样将bson.M + bson.D
放在bson.D
:
filter := bson.M{"$and": bson.D{{"p", 10}, bson.M{"$or": bson.D{{"s", 30}, {"a", 1}}}}}
.. and of course it doesn't work: cannot use primitive.M literal (type primitive.M) as type primitive.E in slice literal
. ..当然它不起作用:
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
如果稍后我尝试
... in []
bson.D
使用... in []
逻辑,可能会发生同样的问题
How do I create such nested queries in Go and official MongoDB driver?如何在 Go 和官方 MongoDB 驱动程序中创建此类嵌套查询?
What matters is that $or
requires an array, which is bson.A
.重要的是
$or
需要一个数组,即bson.A
。 Also $and
is the default, you don't have to indicate that. $and
也是默认值,您不必指明。
Your filter can be defined like this:您的过滤器可以这样定义:
filter := bson.D{
{"p", 10},
{"$or", bson.A{
bson.D{{"s", 30}},
bson.D{{"a", 10}},
}},
}
You may also use this:你也可以使用这个:
filter = bson.D{
{"p", 10},
{"$or", bson.A{
bson.M{"s": 30},
bson.M{"a": 10},
}},
}
Or this:或这个:
filter := bson.M{
"p": 10,
"$or": bson.A{
bson.M{"s": 30},
bson.M{"a": 10},
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.