在Go语言中使用mgo操作MongoDB,如何使用逻辑运算符进行查询?

huangapple go评论82阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2014年11月14日 22:31:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/26932298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定