Search code examples
mongodbgosequential

Sequential queries with golang & mongodb


Wondering what is best way to make sequential queries from Golang for a mongodb. Example lets say you have :

result *bson.M
ids:=["543d171c5b2c12420dd016","543d171c5b2dd016"]
oids := make([]bson.ObjectId, len(ids))
for i := range ids {
  oids[i] = bson.ObjectIdHex(ids[i])
}
query := bson.M{"_id": bson.M{"$in": oids}}
error:= c.Find(query).All(&result)

And you want to take the output of the _ids and use it as a query for another table. So is this correct?

query = bson.M{"_id": bson.M{"$in": result}}

Solution

  • Here's how to construct a query using the ids of documents returned from some other query.

     var docs []bson.M
     if err := c.Find(query).All(&docs); err != nil {
        // handle error
     }
     docIDs := make([]interface{}, len(docs))
     for i := range docs {
        docIds[i] = docs[i]["_id"]
    }
    query = bson.M{"_id": bson.M{"$in": docIDs}}