MongoDB in Go (golang) with mgo: how to use logical operators to query?

后端 未结 2 569
北恋
北恋 2021-02-07 19:32

I would like to run the following query in golang using mgo in a pipeline.

{\"key1\" : 1,
 \"$or\" : [{\"key2\" : 2}, {\"key3\" : 2}]}

I have l

相关标签:
2条回答
  • 2021-02-07 19:49

    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)
    
    0 讨论(0)
  • 2021-02-07 19: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},
        },
    }
    
    0 讨论(0)
提交回复
热议问题