16

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

p.paolo321
  • 193
  • 1
  • 1
  • 7

2 Answers2

46

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},
    },
}
ANisus
  • 74,460
  • 29
  • 162
  • 158
  • Welcome! You missed the array/slice, so the key was []interface{} – ANisus Nov 14 '14 at 15:23
  • I copy pasted your bson.D example and I get "exception: A pipeline stage specification object must contain exactly one field." – FuriousGeorge Feb 03 '15 at 21:19
  • @FuriousGeorge Are you using the query in a `Find` or `Pipe`? The error is a mongodb one, but I haven't played so much with building aggregation pipelines, so I can't tell you right away how to fix it. Sorry. – ANisus Feb 04 '15 at 07:28
  • pipe := collection.Pipe(pipeline) if error := pipe.All(&res); error != nil { t.Fatal(error) } – FuriousGeorge Feb 04 '15 at 15:08
  • Hey, why we cannot using `bson.D` for `[]interface{}`? I guess it's the same thing, right? I've tried it, but It seems the query is not working as expected. Any reason? – nmfzone Nov 09 '22 at 04:53
  • Oh sorry, stupid question. `bson.D` is not `[]interface{}`, `bson.A` does. If we're using `bson.D` instead of `[]interface{}` (since `bson.D` is `[]bson.E`, can't have `bson.D` or `bson.M` inside `bson.D`), then the structure would be different, hence the query will not working. – nmfzone Nov 09 '22 at 05:52
1

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)