更新多个文档并返回所有更新的文档

编程入门 行业动态 更新时间:2024-10-12 16:22:49
本文介绍了更新多个文档并返回所有更新的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种使用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标志更新许多文档,但仅返回 WriteResult 看起来像这样-

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 })

更多推荐

更新多个文档并返回所有更新的文档

本文发布于:2023-11-28 12:14:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642355.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   多个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!