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

MongoDB数组操作问题:如何用aggregate修改指定子文档status

问题:使用MongoDB Aggregate修改数组中指定元素的status值

我需要通过_id在数据库中查找用户,用户的文档结构如下:

{
    "_id": "6381e7c6bf8892cf05c7c798",
    "username": "Teacher",
    "email": "teacher@gmail.com",
    "role": "teacher",
    "avatar": "fixtures/teacher.jpg",
    "token": "KNuSF7sscU3EJsMetUFKi",
    "authentication": true,
    "myCourses": []
}

其中myCourses是数组字段,具体结构如下:

"myCourses": [
    {
        "course": "6381e7c6bf8892cf05c7c7b3",
        "status": true,
        "_id": "6381e80f12d633b2e6c35fbd"
    },
    {
        "course": "6381edab4f212193837ab575",
        "status": true,
        "_id": "6381edc54f212193837ab57c"
    }
]

我的需求是:使用aggregate从myCourses数组中找到指定course字段的对象,并修改它的status值。我尝试了以下几种方法:

  • 方法一:
const test = await User.find({ _id: userId, myCourses: {$elemMatch: {course: courseId}} })
  • 方法二:
const test = await User.find(userId, { courseId: {$in : myCourses} })
  • 方法三:
const updateCourseStatus = user.myCourses.find(elem => elem.course.toString() === courseId)

最后一种方法可以运行,但我认为它并非正确的解决方案。

内容的提问来源于stack exchange,提问作者Александр Тищенко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:25:23