Mongo Go 驱动程序 - 内联嵌入式结构不起作用

Art*_*Art 3 go mongodb bson mongo-go

在开发 Golang Mongo Driver 时,我遇到了这种奇怪的使用行为inline

似乎bson:",inline"不适用于Embedded Structs.

无法理解为什么会有这样的行为?

inline Inline the field, which must be a struct or a map, causing all of its fields or keys to be processed as if they were part of the outer struct. For maps, keys must not conflict with the bson keys of other struct fields.

import (
    "context"
    "encoding/json"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

//Expected Output
//{
//  "ID": "5e6e96cb3cfd3c0447d3e368",
//  "product_id": "5996",
//  "Others": {
//      "some": "value"
//  }
//}

//Actual Output
//{
//  "ID": "5e6e96cb3cfd3c0447d3e368",
//  "product_id": "5996"
//}

type Product struct {
    ID        primitive.ObjectID `bson:"_id"`
    ProductId string             `bson:"product_id" json:"product_id"`
    *SchemalessDocument
}

type SchemalessDocument struct {
    Others    bson.M             `bson:",inline"`
}


func main() {

    clientOptions := options.ClientOptions{
        Hosts: []string{"localhost"},
    }
    client, _ = mongo.NewClient(&clientOptions)
    client.Connect(context.TODO())
    var p Product
    collection := client.Database("Database").Collection("collection")
    query := bson.D{{"product_id", "5996"}}
    _ = collection.FindOne(context.TODO(), query).Decode(&p)

    jsonResp, _ := json.Marshal(p)
    fmt.Println(string(jsonResp))

}
Run Code Online (Sandbox Code Playgroud)

但如果我改变相同的代码就可以工作

type Product struct {
    ID        primitive.ObjectID `bson:"_id"`
    ProductId string             `bson:"product_id" json:"product_id"`
    Others    bson.M             `bson:",inline"`
}
Run Code Online (Sandbox Code Playgroud)

b.b*_*ben 6

这才是应该的

type Product struct {
    ID        primitive.ObjectID `bson:"_id"`
    ProductId string             `bson:"product_id" json:"product_id"`
    *SchemalessDocument          `bson:",inline"`
}

type SchemalessDocument struct {
    Others    bson.M             `bson:"others"`
}

Run Code Online (Sandbox Code Playgroud)