Home > Backend Development > Golang > How to Query Unstructured MongoDB Collections in Go with mgo?

How to Query Unstructured MongoDB Collections in Go with mgo?

Barbara Streisand
Release: 2024-12-26 08:44:14
Original
571 people have browsed it

How to Query Unstructured MongoDB Collections in Go with mgo?

Handling Unstructured MongoDB Collections in Go with mgo

When querying a collection in MongoDB with mgo, it is possible to predefined the data that will be returned in a struct, as demonstrated with the Person struct example provided. However, there may be scenarios where the documents in the collection have a varying set of keys.

How to Handle Unstructured Collections in Go / mgo

There are multiple ways to handle unstructured collections in Go / mgo:

Using a map:

By using a bson.M type, which is a map[string]interface{}, you can store the document data directly without defining a specific struct.

var m bson.M
err := collection.Find(nil).One(&m)
check(err)
for key, value := range m {
    fmt.Println(key, value)
}
Copy after login

Using a document slice:

bson.D is a slice type that preserves the ordering of keys and provides an efficient mechanism for handling documents.

var d bson.D
err := collection.Find(nil).One(&d)
check(err)
for i, elem := range d {
    fmt.Println(elem.Name, elem.Value)
}
Copy after login

Using an inline map field:

By using the ,inline bson flag in a map field in a struct, you can combine the convenience of using a struct with the flexibility of handling unknown fields.

type Person struct {
    ID        bson.ObjectId `bson:"_id,omitempty"`
    Name      string
    Phone     string
    Extra     bson.M `bson:",inline"`
}
Copy after login

The above is the detailed content of How to Query Unstructured MongoDB Collections in Go with mgo?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template