Go语言操作MongoDB如何向空数组追加对象而不替换原有内容
问题修复方案
核心错误原因
- 字段名不匹配:代码中更新的目标字段写为
candidates.votes,但实际集合内对应字段名为voter,这是报错「Cannot create field 'votes'」的直接原因 - 更新操作符使用错误:
$set操作符会直接覆盖目标字段的原有值,要实现数组元素追加,需要使用$push操作符,搭配$each修饰符实现批量元素追加 - 数组元素定位缺失:没有使用
$占位符匹配filter中筛选到的candidates数组下标,无法正确定位到指定name的候选人对应的子字段
修复后的代码
func VoteToSubject(collection *mongo.Collection, title string, name string, voter []Supporter) { // filter 可以简化写法,不需要显式写$and filter := bson.D{ {"title", title}, {"candidates.name", name}, } // 使用$push + $each实现数组追加,$占位符匹配筛选到的candidates数组下标 update := bson.D{ {"$push", bson.D{ {"candidates.$.voter", bson.D{ {"$each", voter}, }}, }}, } updateResult, err := collection.UpdateOne(context.TODO(), filter, update) if err != nil { log.Fatal(err) } fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount) }
额外说明
如果需要避免同一个支持者重复投票,可以用$addToSet操作符替换$push,MongoDB会自动对插入的元素去重,不会插入重复内容。
内容的提问来源于stack exchange,提问作者Darami
相关产品推荐
相关产品推荐

