Home > Article > Backend Development > How to Retrieve MongoDB Documents by an Array of Object IDs using mgo and bson?
Retrieving MongoDB Documents by Array of Object IDs
In MongoDB, it's possible to store an array of object IDs (also known as _ids) within a document. To retrieve all documents corresponding to those object IDs efficiently, use the $in operator.
Question:
You have an array of hex-encoded _ids:
ids := ["543d171c5b2c12420dd016", "543d171c5b2dd016"]
How do you retrieve the corresponding documents using mgo and bson?
Answer:
Your initial approach using:
query := bson.M{"_id": bson.M{"$in": ids}} c.Find(query).All()
is incorrect because the _ids are stored as object IDs, not strings. To retrieve documents by object IDs, you need to convert the hex-encoded strings into bson.ObjectId objects:
oids := make([]bson.ObjectId, len(ids)) for i := range ids { oids[i] = bson.ObjectIdHex(ids[i]) } query := bson.M{"_id": bson.M{"$in": oids}} c.Find(query).All()
This code:
The above is the detailed content of How to Retrieve MongoDB Documents by an Array of Object IDs using mgo and bson?. For more information, please follow other related articles on the PHP Chinese website!