更新多个文档并返回所有更新的文档 [英] Update multiple documents and return all updated documents

查看:53
本文介绍了更新多个文档并返回所有更新的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用mongoose一次更新许多文档并返回所有修改后的文档的方法.我尝试在 update()中设置multi:true.它正在更新所有匹配的文档,但不返回任何文档.然后,我尝试使用 findOneAndUpdate().即使有许多匹配的文档,它也只会更新和返回一个文档.是的,函数名称本身告诉我,它只会更新一个,但我还是尝试过.我无法在findOneAndUpdate()中设置类似multi:true的选项.怎么做到呢?预先感谢

I am looking for a way to update many documents at once using mongoose and return all the modified documents. I tried with setting multi:true in update(). It is updating all matching documents but not returning any. Then I tried with findOneAndUpdate(). It is updating and returning only one document even if there are many matching ones. Yeah, the function name itself tells, it will update only one, still I tried. I could not set option like multi:true in findOneAndUpdate(). How can it be done? Thanks in advance

推荐答案

当前,我认为在MongoDB中不可能更新多个文档并在同一查询中返回所有更新的文档.

Currently I don't think its possible in MongoDB to update multiple documents and return all the updated documents in the same query.

在Mongoose中,findOneAndUpdate()基于MongoDB的本机findAndModify()方法.

In Mongoose, the findOneAndUpdate() is based on the native findAndModify() method of MongoDB.

如果您查看findAndModify()方法的官方文档,它的状态是-

If you check the offical documentation of the findAndModify() method, its states that -

findAndModify命令修改并返回单个文档.

The findAndModify command modifies and returns a single document.

尽管查询可能匹配多个文档,但findAndModify只会选择一个文档进行修改.

Although the query may match multiple documents, findAndModify will only select one document to modify.

因此,您不能使用findAndModify更新多个文档.

Hence, you can not update multiple documents using findAndModify.

update()updateMany()方法使用multi标志更新许多文档,但仅返回

update() or updateMany() method on the other hand updates many documents with the multi flag but it only returns the WriteResult which looks like this -

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

这篇关于更新多个文档并返回所有更新的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆