mongodb - 如何使用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)
})
数组在哪里v
,interface
当我运行在 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)
解决方案
首先,我建议使用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()以执行批量写入操作
推荐阅读
- python - Python。文档字符串是可写的吗?好像是
- elasticsearch - 在 elasticsearch 中监控执行的搜索查询
- python - Python - Matplotlibs - 如何格式化并将间隔添加到具有日期和时间的 X 轴?
- javascript - 我想通过滚动来调整图像大小;但是,我的功能似乎是错误的。如果条件正确,我无法使用
- c# - Unity C# 错误:“类型或命名空间定义,或预期文件结尾”
- hadoop - 如何通过 Helm Chart 在 Kubernetes 中安装 Hadoop?
- python - 基于类的视图和查询集中 request.user 的 Python Django 最佳实践
- r - 使用 R 在 Firefox 中创建当前打开的 URL 的向量
- css - 如何从 Angular (2+) 生成缩小的 css
- installation - 在 R studio 1.2.1335 和 macOS Sierra 10.12.6 中使用 BiocManager::install 安装“org.Hs.eg.db”时出现问题