首页 > 解决方案 > 如何使用golang在mongodb中插入多数组

问题描述

我有这个回调

p.OnSuccess(func(v interface{}) {

    bulk := collections.Bulk()

    bulk.Insert(v)
    _, bulkErr := bulk.Run()
    if bulkErr != nil {
        panic(bulkErr)
    }

    fmt.Printf("\n - %d comments inserted!", reflect.ValueOf(v).Len())
    Response(w, 200, 1, "comment inserted!", v)
})

数组在哪里vinterface当我运行在 mongo 中插入数据的程序时,golang 用以下消息回复我:

BSON 字段 'insert.documents.0' 是错误类型 'array',预期类型 'object ct'

这是结构:

type Comment struct {

    CommentId   int64 `bson:"commentId" json:"commentId"`
    From        UserComment `bson:"from" json:"from"`
    Text        string      `bson:"text" json:"text"`
    CreatedTime time.Time   `bson:"createdTime" json:"createdTime"`
    InfId       string      `bson:"infId" json:"infId"`
    PostDate    string      `bson:"postDate" json:"postDate"`
    PostId      string      `bson:"postId" json:"postId"`
    Rate        string      `bson:"rate" json:"rate"`
    CreatedAt   time.Time   `bson:"createdAt" json:"createdAt"`
    UpdatedAt   time.Time   `bson:"updatedAt" json:"updatedAt"`
}

type UserComment struct {

    InstagramId int64  `bson:"instagramId" json:"instagramId"`
    Username    string `bson:"username" json:"username"`
    FullName    string `bson:"fullName" json:"fullName"`
    Picture     string `bson:"picture" json:"picture"`
}

我不知道是否是结构的格式,但我尝试使用此代码,但它也不起作用!

var (
    Allcomments []Comment
    p           = promise.NewPromise()
)

fc := UserComment{
    InstagramId: 1121313, //c.User.ID,
    Username:    "c.User.Username",
    FullName:    "c.User.FullName",
    Picture:     "c.User.ProfilePicURL",
}

cmmnts := Comment{
    CommentId:   44232323, //c.ID,
    From:        fc,
    Text:        "c.Text",
    CreatedTime: now,
    InfId:       "infId",
    PostDate:    "postDate",
    PostId:      "PostId",
    Rate:        "a",
    CreatedAt:   now,
    UpdatedAt:   now,
}



Allcomments = append(Allcomments, cmmnts)
p.Resolve(Allcomments)

标签: mongodbgomgo

解决方案


首先,我建议使用go.mongodb.org/mongo-driver库与 MongoDB 进行交互。这是 Go 语言的 MongoDB 官方驱动程序。

要插入一个数组,您可以使用Collection.InsertMany()。例如:

result, err := coll.InsertMany(
            context.Background(),
            []interface{}{
                bson.D{
                    {"item", "shirt"},
                    {"quantity", int32(25)},
                    {"tags", bson.A{"blank", "red"}},
                    {"size", bson.D{
                        {"h", 14},
                        {"w", 21},
                        {"uom", "cm"},
                    }},
                },
                bson.D{
                    {"item", "hat"},
                    {"quantity", int32(42)},
                    {"tags", bson.A{"gray"}},
                    {"size", bson.D{
                        {"h", 27.9},
                        {"w", 35.5},
                        {"uom", "cm"},
                    }},
                },
}) 

另请参阅Collection.BulkWrite()以执行批量写入操作


推荐阅读