如何使用 Mongoose 的 updateMany() 函数
如果你想在 Mongoose 中用一个命令更新多个文档,你应该使用 updateMany()
功能。 它最多需要三个参数:
- filter :它应该找到与过滤器匹配的文档。 如果你想更新模型中的所有文档,你可以省略这个参数
- update 应用更新的描述:使用更新运算符
- 选项 :其他可调参数
const testSchema = new mongoose.Schema({
name: String,
location: String
});
const Test = mongoose.model('Test', testSchema);
await Test.create({ name: 'Test Testerson' });
await Test.create({ name: 'Mastering JS' });
await Test.create({ name: 'MeanIT' });
// Set `location` property on all documents
await Test.updateMany({}, { location: 'Florida' });
// Set `location` property on documents whose 'name' starts with 'M'
await Test.updateMany({ name: /^M/ }, { $set: { location: 'Miami' } });
返回值
await Model.updateMany()
返回具有 5 个属性的对象:
acknowledged
:一个布尔值,表示更新操作是否被服务器确认。 见 写疑虑 。modifiedCount
:已更新的文档数。 只有已更新的文档才会包含在此计数中。 例如,如果您将所有文档的名称更改为Test
但有些文件已经有了这个名字Test
,这些文件将不计入该计数。upsertedId
:要么是null
如果必须更新文档,则包含一个 id。upsertedCount
:将反映必须更新的文件数量。matchedCount
:与过滤器匹配的文档数。
await Test.updateMany({}, { location: 'Florida' });
// { acknowledged: true, modifiedCount: 3, upsertedId: null, upsertedCount: 0, matchedCount: 3 }
modifiedCount
总是小于或等于 matchedCount
,modifiedCount
如果某些文档未受更新影响,则可能会更少。 例如,如果你运行上面的更新两次,第二次 modifiedCount
将为 0,因为所有文档都已经有 location
设置为 Florida。
await Test.updateMany({}, { location: 'Florida' });
const res2 = await Test.updateMany({}, { location: 'Florida' });
res2.matchedCount; // 3
res2.modifiedCount; // 0, because no documents were changed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论