How to write mongodb shell query into golang

Viewed 164

I have a mongodb query that I written for shell which is working fine but now I want to transfer it into golang below is the query and solution that I tried

db.getCollection('test').find({"course" : /^ba$/i, "status":{"$ne":0}}).count()

That I tried:-

query := bson.M{"status": bson.M{"$ne": 0}, "course": "/^" + parameter + "$/i"}
query := bson.M{"status": bson.M{"$ne": 0}, "course": `/^` + parameter + `$/i`}

but not working fine can anyone please find mistake that I'm doing.

1 Answers

This is how you could count documents and use regular expressions with golang mongodb driver.


pattern := "test"
count, err := coll.CountDocuments(ctx, bson.D{
    {"course", primitive.Regex{Pattern: "^" + pattern + "$", Options: "i"}},
    {"status", bson.D{{"$ne", 0}}},
})
if err != nil {
    panic(err)
}
fmt.Println(count)
Related