MongoDB中的replaceOne()和updateOne()有什么区别? [英] What's the difference between replaceOne() and updateOne() in MongoDB?

查看:1603
本文介绍了MongoDB中的replaceOne()和updateOne()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB批量操作有两个选项:

MongoDB bulk operations have two options:

  1. Bulk.find.updateOne()

将单个文档更新操作添加到批量操作列表中.该操作可以替换现有文档或更新现有文档中的特定字段.

Adds a single document update operation to a bulk operations list. The operation can either replace an existing document or update specific fields in an existing document.

  • Bulk.find.replaceOne()

    将单个文档替换操作添加到批量操作列表中.使用Bulk.find()方法来指定确定要替换哪个文档的条件. Bulk.find.replaceOne()方法将替换限制为单个文档.

    Adds a single document replacement operation to a bulk operations list. Use the Bulk.find() method to specify the condition that determines which document to replace. The Bulk.find.replaceOne() method limits the replacement to a single document.

  • 根据文档,这两种方法都可以替换匹配的文档.我是否正确理解updateOne()是更通用的方法,它可以像replaceOne()一样完全替换文档,也可以只更新其特定字段?

    According to the documentation, both of these two methods can replace a matching document. Do I understand correctly, that updateOne() is more general purpose method, which can either replace the document exactly like replaceOne() does, or just update its specific fields?

    推荐答案

    使用replaceOne()您只能替换整个文档,而updateOne()允许更新字段.

    With replaceOne() you can only replace the entire document, while updateOne() allows for updating fields.

    由于replaceOne()替换了整个文档-旧文档中未包含在新文档中的字段将丢失.使用updateOne()可以添加新字段,而不会丢失旧文档中的字段.

    Since replaceOne() replaces the entire document - fields in the old document not contained in the new will be lost. With updateOne() new fields can be added without losing the fields in the old document.

    例如,如果您具有以下文档:

    For example if you have the following document:

    {
       "_id" : ObjectId("0123456789abcdef01234567"),
       "my_test_key3" : 3333
    }
    

    使用:

    replaceOne({"_id" : ObjectId("0123456789abcdef01234567")}, { "my_test_key4" : 4})
    

    导致:

    {
       "_id" : ObjectId("0123456789abcdef01234567"),
       "my_test_key4" : 4.0
    }
    

    使用:

    updateOne({"_id" : ObjectId("0123456789abcdef01234567")}, {$set: { "my_test_key4" : 4}})
    

    导致:

    {
       "_id" : ObjectId("0123456789abcdef01234567"),
       "my_test_key3" : 3333.0,
       "my_test_key4" : 4.0
    }
    

    请注意,通过updateOne(),您可以在更新运算符上使用文档.

    Note that with updateOne() you can use the update operators on documents.

    这篇关于MongoDB中的replaceOne()和updateOne()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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