doubi7346 2018-06-27 18:45
浏览 169
已采纳

使用Golang动态查询mongodb

I'm trying to query my mongodb database using golang (and the mgo library) with only one function, and the method I am currently using is:

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

Where items is a map and the key is the name of the field I am searching inthe db, and the value is what I want to search by.

and sel() is:

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

currently it will return all of the results where at least one of the fields matches the input map. (So a logical OR) however I would like it to return the logical AND of these fields.

Does anyone have suggestions on how to modify the existing code or a new way of efficiently querying the database?

Thank you

  • 写回答

1条回答 默认 最新

  • dsa4214 2018-06-27 19:19
    关注

    I don't know what this line is supposed to mean:

    result[ ] = "$in"
    

    As it is a compile-time error.

    But the elements of the query document (the conditions) are in logical AND connection by default, so this is all it takes:

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

    If this gives you all the documents in the collection, then that means all the key-value pairs match all the documents. Experiment with simple filters to see that it works.

    Also note that the mgo package also accepts a wide range of maps and structs, not just bson.M. Documentation of Collection.Find() has this to say about the allowed types:

    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{}.

    So you can use your map which is of type map[string]string without converting it:

    err = c.Find(items).Sort("-createdAt").All(&result)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?