如何使用golang在mongodb中插入多数组

时间:2019-04-08 23:35:01

标签: mongodb go mgo

我有此回调

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”是错误的“数组”类型,预期类型是“ obje”   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)

1 个答案:

答案 0 :(得分:1)

首先,我建议使用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()来执行Bulk Write Operations