You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Go操作MongoDB更新嵌入式数组的最后一项?

问题根因
  • 你的ArrayFilters使用逻辑完全不符合MongoDB语法规范:arrayFilter是用来筛选数组中满足条件的元素,你写的{"s": {"rides": {"$slice", -1}}}规则MongoDB无法识别,没有匹配到任何rides数组中的元素,所以更新操作没有触发数据修改,才会出现Matched 1, Modified 0的输出。
  • 实际上你完全不需要使用ArrayFilter实现这个需求,MongoDB 3.6及以上版本原生支持负下标直接定位数组的最后一个元素,写法更简单高效。
正确实现代码
filter := bson.M{"_id": objectId}
// 可选配置:添加该条件可避免rides数组为空时操作报错
// filter["rides.0"] = bson.M{"$exists": true}

update := bson.M{
    "$push": bson.M{
        "rides.-1.status_history": statusEntry,
    },
}

upsert := true
opts := options.UpdateOptions{
    Upsert: &upsert,
}

result, err := col.UpdateOne(ctx, filter, update, &opts)
if err != nil {
    // 自行处理错误逻辑
}

fmt.Printf("Matched %v, Modified %v, Upserted %v\n",
    result.MatchedCount,
    result.ModifiedCount,
    result.UpsertedCount,
)

内容的提问来源于stack exchange,提问作者rasputinscousin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:54:05