dongxieyou3314 2014-11-14 14:31
浏览 161
已采纳

Go(golang)与mgo中的MongoDB:如何使用逻辑运算符进行查询?

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

  • 写回答

2条回答 默认 最新

  • dongsheng66783619 2014-11-14 14:55
    关注

    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},
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制