Obect field return slice/array after query from DB (6.0.4 Community Edition)

package main

import (
	"context"
	"fmt"
	"time"

	"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"
)

type User struct {
	Id       primitive.ObjectID `bson:"_id,omitempty"`
	Identity string             `bson:"Identity,omitempty"`
	Name     string             `bson:"Name,omitempty"`
	Age      int                `bson:"Age,omitempty"`
}

type Log struct {
	Id         primitive.ObjectID `bson:"_id,omitempty"`
	CreatedAt  time.Time          `bson:"CreatedAt,omitempty"`
	CreatedBy  string             `bson:"CreatedBy,omitempty"`
	ModelValue interface{}        `bson:"ModelValue,omitempty"`
}

func main() {
	results := []*Log{}

	user := new(User)
	user.Id = primitive.NewObjectID()
	user.Identity = "E00000001"
	user.Name = "test user"

	log := new(Log)
	log.CreatedAt = time.Now()
	log.ModelValue = user
	log.CreatedBy = "E00000SYS"

	ctx := context.Background()
	mongoClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27018"))
	if err != nil {
		fmt.Println("Create client failed: ", err)
	}

	mongoColl := mongoClient.Database("mongo_test").Collection("Log")
	_, err = mongoColl.InsertOne(ctx, log)
	if err != nil {
		fmt.Printf("Create document with error: %v\n", err)
	}

	cursor, _ := mongoColl.Find(context.Background(), bson.M{})
	cursor.All(ctx, &results)
	for _, v := range results {
		fmt.Println(v.ModelValue)
	}
}

Query results (with bson.D):

[{_id ObjectID("64128ad91f13069952432f7f")} {Identity E00000001} {Name test user}]

Expected:

map[_id ObjectID("64128ad91f13069952432f7f") Identity E00000001 Name 'test user']

How can I return the ModelValue as bson.M instead of bson.D by default?

Thanks

@chengkun_kang thanks for the question!

Starting in Go Driver v1.12.0, you can use SetBSONOptions to override the default BSON marshal and unmarshal behavior for a Client.

For example, to always unmarshal to bson.M when there is no type information, set DefaultDocumentM to true:

mongoClient, err := mongo.Connect(
	context.Background(),
	options.Client().
		ApplyURI("mongodb://localhost:27018").
		SetBSONOptions(&options.BSONOptions{
			DefaultDocumentM: true,
		}))
// ...