Mongo中的foreach
发布时间:2026-11-30 11:35:07 浏览:99 次
MongoDB中的$forEach操作符用于遍历数组,并对数组中的每个元素执行(xing)指定的操作,它通常与$update操作一起使用(yong),以(yi)便在更(geng)新文档时对数组中(zhong)的每个元素执行操作。(图片(pian)来源网络,侵删)
以下是一个简单的示例:

假设我们有一个(ge)名为students的集合(he),其中(zhong)包含以下文(wen)档:

{ "_id": 1, "name": "张三", "scores": [80, 90, 85]},{ "_id": 2, "name": "李四", "scores": [70, 60, 75]}现在,我(wo)们想要将每个学生的分数提高10分(fen),我们可以使(shi)用$forEach和$update操作来实现这个目标:

db.students.updateMany( { }, [ { "$set": { "scores": { "$map": { "input": "$scores", "as": "score", "in": { "$add": ["$$score", 10] } } } } } ])在这个示(shi)例中,我们首先使用$updateMany操作来匹配所有文档,我(wo)们使用$set操作来更新scores字段,接下来,我们使用$map操作符来遍历scores数组,并为每个元素应用一个表达式,在这个表达式中(zhong),我们使用$add操作符将当前分数($$score)加上10。
执行上述代码后,students集合中的文(wen)档将更新为:
{ "_id": 1, "name": "张三", "scores": [90, 100, 95]},{ "_id": 2, "name": "李四", "scores": [80, 70, 85]}

您的当前位置: