Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object(Interface{})字段Query结果返回Slice/Array #283

Open
chengkun-kang opened this issue Mar 16, 2023 · 1 comment
Open

Object(Interface{})字段Query结果返回Slice/Array #283

chengkun-kang opened this issue Mar 16, 2023 · 1 comment
Labels
question Further information is requested

Comments

@chengkun-kang
Copy link

chengkun-kang commented Mar 16, 2023

MongoDB 6.0.4 Community Edition

main.go

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/qiniu/qmgo"
	"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()
	client, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: "mongodb://localhost:27018"})
	if err != nil {
		fmt.Println("Create client failed: ", err)
	}

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

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

Document in mongo db:
image

Query ModelValue field result:
image

Q:
怎样ModelValue可以返回bson.M (map[string]interface{})而不是bson.D ([]bson.E)?

谢谢!

@jiangz222
Copy link
Collaborator

这个是mongodb官方行为,qmgo暂时不会改变这个行为

@jiangz222 jiangz222 added the question Further information is requested label May 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants