【发布时间】:2021-09-14 23:35:30
【问题描述】:
我想在 mongodb 上做更新操作。 Mongodb 查询由 arrayList 组成: 我想实现 endexamfunction 它将简单地增加尝试计数 我的学习者文档,例如 Learner contains [] course , course contains []exam & Exam contains attemptcount
查询:
db.learner.updateOne(
{
"username": "USERNAME",
},
{
$inc : {
"courses.$[i].exams.$[j].attemptscompleted":1,
}
},
{
arrayFilters: [
{"i.coursename": "COURSENAME"},
{"j.examid": "EXAMID"}
]
}
)
在 golang 中,我将用户名、课程名和考试作为参数。 这就是我的 golang 函数的样子:
func EndExam(username, coursename, examid string) {
client, err := connectionHelper.GetMongoClient()
if err != nil {
return nil, err
}
collection := client.Database(connectionHelper.DB).Collection(connectionHelper.LEARNER)
res := collection.FindOneAndUpdate(
context.Background(),
bson.D{
{Key: "username", Value: username},
},
bson.D{
{Key: "$inc", Value: bson.D{
{Key: "courses.$[i].exams.$[j].attemptscompleted", Value: 1},
}},
},
options.FindOneAndUpdate().SetArrayFilters(options.ArrayFilters{
Filters: []interface{}{bson.D{
{Key: "i.coursename", Value: coursename},
{Key: "j.examid", Value: examid},
}},
}).SetReturnDocument(1),
)
fmt.Println(res)
}
我收到错误:&{{9 解析数组过滤器时出错 :: 由 :: 预期单个顶级字段名称,找到 'i' 和 'j' [] FailedToParse } [] }
看起来我弄乱了arrayfilter。但我不知道如何在这种情况下使用它们。我正在寻找解决方案或在 golang 中查看此查询的更好方法
【问题讨论】:
标签: database mongodb go aggregation-framework