Home  >  Article  >  Backend Development  >  Mongodb storage and retrieval in mongogo driver

Mongodb storage and retrieval in mongogo driver

PHPz
PHPzforward
2024-02-06 09:39:071004browse

mongogo 驱动程序中的 Mongodb 存储和检索

Question content

I am trying to insert data and read that data from mongodb using mongo go driver. I'm using a structure with data fields. When I use the data type as an interface I get multiple maps and when I specify it as a map slice it returns a single map. Data in mongodb is similar.

package main

import (
    "context"
    "fmt"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Host struct {
    Hostname string                   `bson:"hostname"`
    Data     []map[string]interface{} `bson:"data"` //return single map
    // Data     interface{} `bson:"data"` //returns multiple maps

}

func main() {
    // Set up a MongoDB client
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.Background(), clientOptions)
    if err != nil {
        panic(err)
    }

    // Set up a MongoDB collection
    collection := client.Database("testdb").Collection("hosts")

    // Create a host object to insert into the database
    host := Host{
        Hostname: "example.com",
        Data: []map[string]interface{}{
            {"key1": "using specific type", "key2": 123},
        },
    }

    // Insert the host object into the collection
    _, err = collection.InsertOne(context.Background(), host)
    if err != nil {
        panic(err)
    }

    // Query the database for the host object
    filter := bson.M{"hostname": "example.com"}
    var result Host
    err = collection.FindOne(context.Background(), filter).Decode(&result)
    if err != nil {
        panic(err)
    }

    // Print the host object
    fmt.Println(result)
}

When using interface only

When using map tiles

The data stored in both cases is similar.

Why do we get data discrepancies when we try to access the data?


Correct answer


When you use interface{} it means you will let the driver choose what it thinks best represents the data from mongodb Any data type of the arriving data.

When you use []map[string]interface{} you explicitly indicate that you want a map slice, where each map can represent a document.

When you use interface{}, you say nothing. The driver will choose bson.a to represent an array and bson.d to represent a document.

bson.a a> is just a [] interface{}, and bson.d is []e where e is

type e struct {
    key   string
    value interface{}
}

So basically bson.d is an ordered list of key-value pairs (properties).

So when you use interface{} you get one slice instead of multiple maps. Without printing type information, the fmt package prints slices and maps, both enclosed in square brackets.

If you want to see the type, print like this:

fmt.printf("%#v\n", result.data)

Output when using []map[string] interface {}:

[]map[string]interface {}{map[string]interface {}{"key1":"using specific type", "key2":123}}

Output when using interface{}:

primitive.A{primitive.D{primitive.E{Key:"key1", Value:"using specific type"}, primitive.E{Key:"key2", Value:123}}}

The above is the detailed content of Mongodb storage and retrieval in mongogo driver. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete