dongxieyou3314
dongxieyou3314
2014-11-14 14:31

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 dongsheng66783619 7年前

    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},
        },
    }
    
    点赞 评论 复制链接分享
  • dousilie9522 dousilie9522 3年前

    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)
    
    点赞 评论 复制链接分享

相关推荐