Home >Backend Development >Golang >How to Query MongoDB from Go with an Array of Object IDs?

How to Query MongoDB from Go with an Array of Object IDs?

DDD
DDDOriginal
2024-11-03 00:42:29354browse

How to Query MongoDB from Go with an Array of Object IDs?

Querying MongoDB from Go with Array of Object IDs

In MongoDB, retrieving documents based on their object identifiers stored in an array can be achieved with the $in operator and the mgo and bson packages.

Implementing the Query:

To perform the query correctly, you need to ensure that the object identifiers in the array are in the correct format. If the documents are stored with string IDs, the query you provided was accurate:

<code class="go">query := bson.M{"_id": bson.M{"$in": ids}}
c.Find(query).All()</code>

However, if the object identifiers are in the form of hex-encoded strings (e.g., "543d171c5b2c12420dd016"), you need to convert them to bson.ObjectId objects before using them in the query. Here's how you can do that:

<code class="go">oids := make([]bson.ObjectId, len(ids))
for i := range ids {
  oids[i] = bson.ObjectIdHex(ids[i])
}
query := bson.M{"_id": bson.M{"$in": oids}}</code>

This modification ensures that the query matches the object identifiers stored in the array as bson.ObjectId objects.

The above is the detailed content of How to Query MongoDB from Go with an Array of Object IDs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn