我有一个文档IDarray.数组是有序的,我想要更新所有匹配文档的一个固定的order%.值order应为数组中的位置.

目前,我做了以下工作,这些工作都很好:

const result = await this.collection.bulkWrite(
      orderedIncices.map((_id, index: number) => ({
        updateOne: {
          filter: { _id },
          update: { $set: { order: index } },
        },
      })),
    );

我想知道有没有更有效的方法.

推荐答案

根据 comments 中的建议进行了更新.

你的方法仍然很好,但你也可以使用100功能.

.update({
      _id: {
         $in: orderedIndexes
      }
    },
    [
        {
            $set: {
                order: {
                    $indexOfArray: [orderedIndices, "$_id"]
                }
            }
        }
    ],
    {
        multi: true
    }
)

Note how in this case 100 is used to find the index of the 101 of each document in the 102 array and it is this 101 value that is then used to update the related order field.

Mongodb相关问答推荐

在MongoDB中是否可以按递增顺序更新多个文档?

Golang中的Mongo中值运算

MongoDB shell:如何删除列表以外的所有集合

有没有一种方法可以找到一个文档并通过 Go 更改 mongodb 中的 id/value 来克隆它

聚合 $accumulator + $project

在 MongoDB 中使用 findOneAndUpdate 有条件地更新/更新嵌入式数组

如何过滤查找mongodb的结果

Meteor mongo 驱动程序可以处理 $each 和 $position 运算符吗?

如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId

Spring Mongodb @DBREF

mongodb无法启动

为多个日期范围聚合 $group

java.lang.IncompatibleClassChangeError:Implementing class Mongo

如何从 node.js 以编程方式执行 mongodump 命令?

Mongoimport json 文件更新或覆盖..?

mongoose字符串到 ObjectID

MongoDB:查询和检索嵌入式数组中的对象?

Mongo:匹配聚合查询中的日期似乎被忽略了

从 nodejs 到 mongodb 或 mongoose 的动态数据库连接

错误:需要数据和盐参数