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

MongoDB文档更新无报错但未生效的问题排查求助

MongoDB更新文档匹配数为0的排查与解决

问题现象

更新MongoDB的Course文档时,既无报错也无更新效果,日志显示MatchedCount、ModifiedCount均为0。已尝试UpdateMany、UpdateOne、UpdateByID等方法,手动传入ID字符串也无效。

请求JSON片段:

{
    "id": "649411c5d1c770dd462bd181",
    "title": "Algorithms",
    "description": "An awesome course"
}

代码片段:

type Course struct {
    ObjectId    primitive.ObjectID `bson:"_id, omitempty"`
    Id          string             `json:"id"`
    Title       string             `json:"title"`
    Description string             `json:"description"`
    Lessons     string             `json:"lessons"`
    Duration    string             `json:"duration"`
    Details     struct {
        Title             string `json:"title"`
        Instructor        string `json:"instructor"`
        Introduction      string `json:"introduction"`
        Topics            string `json:"topics"`
    } `json:"course_details"`
}

func (r *CourseRepo) UpdateCourse(ctx context.Context, c *Course) error {
    clog := log.GetLoggerFromContext(ctx)

    objID, err := primitive.ObjectIDFromHex(c.Id)
    if err != nil {
       return err
    }

   filter := bson.D{
     {"_id", objID},
   }

    update := bson.D{
        {"$set", bson.D{
            {"title", c.Title},
            {"description", c.Description},
            {"lessons", c.Lessons},
            {"duration", c.Duration},
            {"course_details", c.Details},
        },
        },
    }

    clog.InfoCtx("Filter: %+v", log.Ctx{"filter ": filter})
    clog.InfoCtx("Update: %+v", log.Ctx{"update ": update})

    result, err := r.collection.UpdateByID(ctx, filter, update)
    if err != nil {
        clog.Error(err)

        return err
    }

    clog.InfoCtx("Update Result", log.Ctx{"result ": result})

    return nil
}

日志信息:

"msg":"Update Result","result ":{"MatchedCount":0,"ModifiedCount":0,"UpsertedCount":0,"UpsertedID":null}}

核心问题与解决步骤

  • UpdateByID传参错误
    UpdateByID的第一个参数应为ObjectID类型的文档ID,而非bson.D格式的filter。当前代码把包装后的filter传入,导致MongoDB尝试匹配_id等于该bson.D对象的文档,自然无匹配。
    修正代码:

    // 直接传入objID,无需包装成bson.D
    result, err := r.collection.UpdateByID(ctx, objID, update)
    
  • 结构体bson标签格式错误
    Course结构体中ObjectId字段的bson标签存在多余空格:bson:"_id, omitempty",正确写法应为bson:"_id,omitempty"(逗号后无空格),否则标签解析异常,可能导致文档序列化/反序列化出错。
    修正结构体字段:

    ObjectId    primitive.ObjectID `bson:"_id,omitempty"`
    
  • 确认目标文档存在
    手动在MongoDB客户端执行查询,验证_id为ObjectId("649411c5d1c770dd462bd181")的Course文档是否真实存在:

    db.courses.find({_id: ObjectId("649411c5d1c770dd462bd181")})
    
  • 检查字段名匹配性
    确认更新语句中的字段名(如title、course_details)与MongoDB实际存储的字段名完全一致(MongoDB字段名区分大小写)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:52:26