英文:
MongoDB in Go (golang) with mgo: how to use logical operators to query?
问题
我想在使用mgo的golang中运行以下查询的管道:
{"key1" : 1,
"$or" : [{"key2" : 2}, {"key3" : 2}]}
我已经到处查找,但找不到类似的示例。我尝试了许多不同的组合,例如:
...
pipeline := []bson.M{
bson.M{"$match" : bson.M{"key1" : 1,
"$or" : bson.M{"key2" : 2, "key3" : 2}}},
...
}
这个代码可以正确编译,但是没有找到任何结果。有什么想法吗?
提前谢谢你。
英文:
I would like to run the following query in golang using mgo in a pipeline.
{"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
答案1
得分: 46
你的Mongo查询可以翻译成以下内容:
pipeline := bson.D{
{"key1", 1},
{"$or", []interface{}{
bson.D{{"key2", 2}},
bson.D{{"key3", 2}},
}},
}
在Mongo控制台中,查询应该等同于以下内容:
db.mycollection.find({"key1" : 1, "$or" : [{"key2" : 2}, {"key3" : 2}]})
如果你更喜欢使用无序映射bson.M
,可以这样写:
pipeline := bson.M{
"key1": 1,
"$or": []interface{}{
bson.M{"key2": 2},
bson.M{"key3": 2},
},
}
英文:
Your mongo query can be translated to the following:
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:
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:
pipeline := bson.M{
"key1": 1,
"$or": []interface{}{
bson.M{"key2": 2},
bson.M{"key3": 2},
},
}
答案2
得分: 1
以下是翻译好的内容:
go语言使用MongoDB进行或查询
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)
英文:
>go lang Mongo db Or query
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论