我有这个回调
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)
})
其中v
是一个interface
数组,当我运行程序在mongo中插入数据时,golang用以下消息回复我:
BSON field 'insert.documents.0' is the wrong type 'array', expected type '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)
最佳答案
首先,我建议使用 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"},
}},
},
})
关于mongodb - 如何使用golang在mongodb中插入多数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55583184/