How to Query MongoDB from Golang using an Array of Object IDs?

DDD
Release: 2024-10-31 02:06:29
Original
555 people have browsed it

How to Query MongoDB from Golang using an Array of Object IDs?

Querying MongoDB from Golang Using an Array of Object IDs

In MongoDB, you can store arrays of documents, each with its own unique _id. This allows you to associate multiple documents with a parent document. When querying for these documents using Golang's mgo and bson packages, it's important to convert the _id array to the appropriate type.

Solution

If the _id values in the array are simply hex strings, the provided code is correct:

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

However, if the _id values are object identifiers (ObjectId), you need to convert them to the proper type:

<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>
Copy after login

This conversion is necessary because the $in operator requires an array of ObjectId values, not hex strings. By converting the hex strings to ObjectId types, you can correctly query for the documents associated with the provided _id values.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!