Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 415
p.paolo321 Avatar asked Nov 14 '14 14:11

p.paolo321


People also ask

What is logical operator in MongoDB?

MongoDB logical operators can be used to filter data based on given conditions. These operators provide a way to combine multiple conditions. Each operator equates the given condition to a true or false value. Joins two or more queries with a logical AND and returns the documents that match all the conditions.


1 Answers

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},
    },
}
like image 171
ANisus Avatar answered Sep 19 '22 08:09

ANisus