In MongoDB, I have a $ in operator that retrieves a document that corresponds to one of several values. This time I will write what to do when you want to use $ in
with mongo-go-driver.
As mentioned in the article How to use the elements of a slice in bson.A using mongo-go-driver 0.2.0, make the value of the array following $ in
type bson.A
. And set. As stated in the here documentation, bson.A
is the type that handles arrays in queries.
Only the setting part of the query is described as a sample. I will omit the description up to the collection acquisition, so please refer to the article I tried using the official MongoDB Go Driver by @ yotahada-nus3 for details. As the content, refill the slice that holds the content of "_id" you want to narrow down to bson.A type and set it in the query.
sample.go
func SampleGetByIDs(ids []string) error {
//Collection acquisition process is omitted ...
idBsonA := bson.A{}
for _, id := range ids {
idBsonA = append(idBsonA, id)
}
filter := bson.D{{Key: "_id", Value: bson.D{{Key: "$in", Value: idBsonA}}}}
cur, err := col.Find(context.Background(), filter)
//The cur acquisition process is omitted ...
}
Recommended Posts