Mongodb request from golang using _id stored in array

So here is my question. I have an array that stores _idsmongodbs objects. What is the correct way to get them all in one request using the mgo and bson package?

So, if the array is like this: ids:=["543d171c5b2c12420dd016","543d171c5b2dd016"]

How do we make a request? I tried this, but I know this is wrong.

query := bson.M{"_id": bson.M{"$in": ids}}
c.Find(query).All()

Thanks in advance

+1
source share
1 answer

If documents are stored with line identifiers, the code looks correct.

IDs look like identifiers for hex encoded objects. If the object identifiers are object identifiers, you need to convert the hexadecimal strings to the object identifiers:

oids := make([]bson.ObjectId, len(ids))
for i := range ids {
  oids[i] = bson.ObjectIdHex(ids[i])
}
query := bson.M{"_id": bson.M{"$in": oids}}
+7
source

Source: https://habr.com/ru/post/1690430/


All Articles