用golang动态查询mongodb

Dynamically query mongodb with golang

我正在尝试使用 golang(和 mgo 库)查询我的 mongodb 数据库,只有一个函数,我目前使用的方法是:

er = c.Find(sel(items)).Sort("-createdAt").All(&result)

其中 items 是一个映射,key 是我在数据库中搜索的字段名称,value 是我要搜索的内容。

而 sel() 是:

func sel(query map[string]string) bson.M {
result := make(bson.M, len(query))
result[ ] = "$in"
for k, v := range query {
    result[k] = v
}
return result

目前它将 return 至少有一个字段与输入映射匹配的所有结果。 (所以是逻辑或)但是我希望它 return 这些字段的逻辑与。

有没有人对如何修改现有代码或有效查询数据库的新方法有建议?

谢谢

我不知道这行是什么意思:

result[ ] = "$in"

因为是编译时错误。

但是查询文档的元素(条件)默认是逻辑AND连接,所以只需要这样:

func sel(query map[string]string) bson.M {
    result := make(bson.M, len(query))
    for k, v := range query {
        result[k] = v
    }
    return result
}

如果这为您提供了集合中的所有文档,则意味着所有键值对都匹配所有文档。试用简单的过滤器,看看它是否有效。

另请注意,mgo package also accepts a wide range of maps and structs, not just bson.M. Documentation of Collection.Find() 对允许的类型有以下说明:

The document may be a map or a struct value capable of being marshalled with bson. The map may be a generic one using interface{} for its key and/or values, such as bson.M, or it may be a properly typed map. Providing nil as the document is equivalent to providing an empty document such as bson.M{}.

因此您可以使用 map[string]string 类型的地图而无需转换它:

err = c.Find(items).Sort("-createdAt").All(&result)