[英]MongoDB in Go (golang) with mgo: how to use logical operators to query?
I would like to run the following query in golang using mgo in a pipeline. 我想在管道中使用mgo在golang中运行以下查询。
{"key1" : 1,
"$or" : [{"key2" : 2}, {"key3" : 2}]}
I have looked everywhere, but I cannot find an example like this. 我到处寻找,但我找不到这样的例子。 I have tried many different combinations, for example: 我尝试了很多不同的组合,例如:
...
pipeline := []bson.M{
bson.M{ "$match" : bson.M{ "key1" : 1,
"$or" : bson.M{ "key2" : 2, "key3" : 2},
}
...
}
which compiles correctly, does not find anything. 编译正确,没有找到任何东西。 Any ideas? 有任何想法吗?
Thank you in advance 先感谢您
Your mongo query can be translated to the following: 您的mongo查询可以转换为以下内容:
pipeline := bson.D{
{"key1", 1},
{"$or", []interface{}{
bson.D{{"key2", 2}},
bson.D{{"key3", 2}},
}},
}
The query should be equivalent to the following in the mongo console: 该查询应该等同于mongo控制台中的以下内容:
db.mycollection.find({"key1" : 1, "$or" : [{"key2" : 2}, {"key3" : 2}]})
If you'd rather wish to use unordered maps, bson.M
, it would be like this: 如果您更愿意使用无序地图, bson.M
,它将是这样的:
pipeline := bson.M{
"key1": 1,
"$or": []interface{}{
bson.M{"key2": 2},
bson.M{"key3": 2},
},
}
go lang Mongo db Or query go lang Mongo db或查询
findQuery := bson.M{"key1" : 1}
orQuery := []bson.M{}
orQuery := append(orQuery, bson.M{"key2" : 2}, bson.M{"key3" : 2})
findquery["$or"] = orQuery
result := []interface{}
err := mongo.DB.C("collectionName").find(findQuery).All(&result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.