Search code examples
gomongo-go

Dynamic BSON creation in Golang MongoDb driver


I am using following BSON for a filter query.

id1, _ := primitive.ObjectIDFromHex("5da34e9037c3bed2f5409489")
id2, _ := primitive.ObjectIDFromHex("5da3511c37c3bed2f540948a")

filter := bson.D{{"_id", bson.D{{"$in", bson.A{id1, id2}}}}}

We have only id1 and id2 for now, but in future there will be id3 , id4.

How to create dynamic BSON and pass it in filter?


Solution

  • bson.A is simply an array:

    var idarr bson.A
    for _,x:=range ids {
       a=append(a,primitive.ObjectIDFromHex(x))
    }
    inQuery:=bson.D{"$in":idarr}