我正在尝试插入数据并使用 mongo go 驱动程序从 mongodb 读取该数据。我正在使用一个具有数据字段的结构。当我使用数据类型作为接口时,我会得到多个映射,当我将其指定为映射切片时,它会返回单个映射。 mongodb 中的数据类似。
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)
}
仅使用接口时
当使用地图切片时
两种情况下存储的数据相似。
为什么当我们尝试访问数据时会出现数据差异?
正确答案
当您使用 interface{}
时,这意味着您将由驱动程序来选择它认为最能代表从 mongodb 到达的数据的任何数据类型。
当您使用 []map[string]interface{}
时,您明确表示您想要一个地图切片,其中每个地图可以代表一个文档。
当您使用 interface{}
时,您什么也不说。驱动程序将选择 bson.a
来表示数组,并选择 bson.d
来表示文档。
bson.a
a> 只是一个 [] 接口{}
,并且 bson.d
是 []e
其中 e
是
type e struct {
key string
value interface{}
}
所以基本上 bson.d
是键值对(属性)的有序列表。
因此,当您使用 interface{}
时,您会得到一片切片,而不是多个地图。不打印类型信息,fmt
包打印切片和地图,两者都括在方括号中。
如果您想查看类型,请像这样打印:
fmt.printf("%#vn", result.data)
使用[]map[string]接口{}
时的输出:
[]map[string]interface {}{map[string]interface {}{"key1":"using specific type", "key2":123}}
使用 interface{}
时的输出:
primitive.A{primitive.D{primitive.E{Key:"key1", Value:"using specific type"}, primitive.E{Key:"key2", Value:123}}}