search

Home  >  Q&A  >  body text

问下 MongoDB 中有没有批量查找文档的同时然后更新文档指定字段值的功能?

现在有一个需求是使用 MongoDB 查找文档的同时将文档中的字段给更新掉,也就是用一个命令完成查找以及更新(原子性)。
Mongo 中对于单个文档是有类似的方法的,比如 FindAndModify 查找并更新的操作,并且是原子性的,但是只作用于单个文档。
问下有没有可以实现查找多个文档并且相应的更新文档的字段的操作。

为情所困为情所困2754 days ago641

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-02 09:27:48

    Mongoose update can be operated in batches. The multi attribute of update is set to true, http://www.nonb.cn/blog/nodej...

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-02 09:27:48

    1. Atomicity in MongoDB:

    1. It is atomic for a single document. FindAnyModify only operates one document, so it is atomic;

    2. For operations on multiple documents, each operation on a single document is atomic, but the entire operation is not atomic. During the operation, there may be operations from other documents.

    But in most scenarios, the atomicity of a single document already meets the requirements;

    If you need to achieve atomicity for the operation of multiple documents, you need to implement it with your own code/design.

    2. For your expressed needs, you can actually use the multi option of update, or directly use updateMany.

    db.collection.updateMany()
    
    db.collection.update(,{multi : true})
    

    For reference.

    Love MongoDB! Have Fun!

    reply
    0
  • Cancelreply