Querying MongoDB from Go Using an Array of Object IDs
In MongoDB, documents can have their IDs stored in an array of strings or Object IDs. When using the mgo package to retrieve multiple documents based on their Object IDs stored in an array, it is important to ensure the correct approach is followed.
Incorrect Query
The provided query:
query := bson.M{"_id": bson.M{"$in": ids}}
is not correct for Object IDs because ids is an array of strings. MongoDB expects Object IDs for the $in operator.
Correct Query for Object IDs
To query for Object IDs stored in an array, convert the strings to Object IDs before constructing the query:
oids := make([]bson.ObjectId, len(ids)) for i := range ids { oids[i] = bson.ObjectIdHex(ids[i]) } query := bson.M{"_id": bson.M{"$in": oids}}
The for loop iterates over the array of strings, converting each one to an Object ID using bson.ObjectIdHex(string) and storing it in the oids slice. The resulting oids slice will contain the Object IDs. The query is then constructed using the oids slice for the $in operator.
By using the correct query for Object IDs, you can retrieve multiple documents with matching IDs efficiently from MongoDB using Go and the mgo package.
The above is the detailed content of How to Query MongoDB from Go Using an Array of Object IDs?. For more information, please follow other related articles on the PHP Chinese website!