• 批量更新 MongoDB 中的文档


    1. 概述

    在本教程中,我们将着眼于在MongoDB中执行批量更新和插入操作。此外,MongoDB 提供 API 调用,允许在单个操作中插入或检索多个文档。MongoDB 使用ArrayBatch接口,通过减少客户端和数据库之间的调用次数,极大地提高了数据库性能。

    在本教程中,我们将研究使用 MongoDB Shell 和 Java 驱动程序代码的解决方案。

    让我们深入研究在 MongoDB 中实现文档的批量更新

    2. 数据库初始化

    首先,我们需要连接到 mongo shell:

    mongo --host localhost --port 27017
    
    • 1

    现在,建立一个数据库baeldung和一个样本收集人口

    use baeldung;
    db.createCollection(populations);
    
    • 1
    • 2

    让我们使用insertMany方法将一些样本数据添加到集合总体中:

    db.populations.insertMany([
    {
        "cityId":1124,
        "cityName":"New York",
        "countryName":"United States",
        "continentName":"North America",
        "population":22
    },
    {
        "cityId":1125,
        "cityName":"Mexico City",
        "countryName":"Mexico",
        "continentName":"North America",
        "population":25
    },
    {
        "cityId":1126,
        "cityName":"New Delhi",
        "countryName":"India",
        "continentName":"Asia",
        "population":45
    },
    {
        "cityId":1134,
        "cityName":"London",
        "countryName":"England",
        "continentName":"Europe",
        "population":32
    }]);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    上面的insertMany查询将返回以下文档:

    {
        "acknowledged" : true,
        "insertedIds" : [
            ObjectId("623575049d55d4e137e477f6"),
            ObjectId("623575049d55d4e137e477f7"),
            ObjectId("623575049d55d4e137e477f8"),
            ObjectId("623575049d55d4e137e477f9")
        ]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里,我们在上述查询中插入了四个文档来执行 MongoDB 中所有类型的写入批量操作。

    数据库baeldung已成功创建,所有需要的数据也已插入到 collection population中,因此我们已准备好执行批量更新。

    3. 使用 MongoDB Shell 查询

    MongoDB 的批量操作构建器用于为单个集合构建批量写入操作列表。我们可以通过 2 种不同的方式初始化批量操作。方法initializeOrderedBulkOp用于在写操作的有序列表中执行批量操作。initializeOrderedBulkOp的缺点之一是,如果在处理任何写入操作时发生错误,MongoDB 将返回而不处理列表中剩余的写入操作。

    我们可以使用插入、更新、替换和删除方法在单个数据库调用中执行不同类型的操作。作为说明,让我们看看使用 MongoDB shell 的批量写入操作查询:

    db.populations.bulkWrite([
        { 
            insertOne :
                { 
                    "document" :
                        {
                            "cityId":1128,
                            "cityName":"Kathmandu",
                            "countryName":"Nepal",
                            "continentName":"Asia",
                            "population":12
                        }
                }
        },
        { 
            insertOne :
                { 
                    "document" :
                        {
                            "cityId":1130,
                            "cityName":"Mumbai",
                            "countryName":"India",
                            "continentName":"Asia",
                            "population":55
                        }
                }
        },
        { 
            updateOne :
                { 
                    "filter" : 
                         { 
                             "cityName": "New Delhi"
                         },
                     "update" : 
                         { 
                             $set : 
                             { 
                                 "status" : "High Population"
                             } 
                         }
                }
        },
        { 
            updateMany :
                { 
                    "filter" : 
                         { 
                             "cityName": "London"
                         },
                     "update" : 
                         { 
                             $set : 
                             { 
                                 "status" : "Low Population"
                             } 
                         }
                }
        },
        { 
            deleteOne :
                { 
                    "filter" : 
                        { 
                            "cityName":"Mexico City"
                        } 
                }
        },
        { 
            replaceOne :
                {
                    "filter" : 
                        { 
                            "cityName":"New York"
                        },
                     "replacement" : 
                        {
                            "cityId":1124,
                            "cityName":"New York",
                            "countryName":"United States",
                            "continentName":"North America",
                            "population":28
                        }
                 }
        }
    ]);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    上面的bulkWrite查询将返回以下文档:

    {
        "acknowledged" : true,
        "deletedCount" : 1,
        "insertedCount" : 2,
        "matchedCount" : 3,
        "upsertedCount" : 0,
        "insertedIds" : 
            {
                "0" : ObjectId("623575f89d55d4e137e477f9"),
                "1" : ObjectId("623575f89d55d4e137e477fa")
            },
        "upsertedIds" : {}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里,在上面的查询中,我们执行了所有类型的写操作,即insertOneupdateOnedeleteOnereplaceOne

    首先,我们使用insertOne方法将一个新文档插入到集合中。其次,我们使用updateOne来更新cityName “New Delhi”的文档。后来,我们使用了deleteOne方法,根据过滤器从集合中删除了一个文档。最后,我们使用replaceOne 来替换带有过滤器cityName “New York”的完整文档。

    4.使用Java驱动

    我们已经讨论了执行批量写操作的MongoDB shell查询。在创建大容量写操作之前,让我们先创建一个MongoClient连接,连接数据库baeldung的集合人口:

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase database = mongoClient.getDatabase("baeldung");
    MongoCollection<Document> collection = database.getCollection("populations");
    
    • 1
    • 2
    • 3

    在这里,我们创建了与 MongoDB 服务器的连接,在默认端口 27017 上运行。现在让我们使用 Java 代码实现相同的批量操作:

    List<WriteModel<Document>> writeOperations = new ArrayList<WriteModel<Document>>();
    writeOperations.add(new InsertOneModel<Document>(new Document("cityId", 1128)
      .append("cityName", "Kathmandu")
      .append("countryName", "Nepal")
      .append("continentName", "Asia")
      .append("population", 12)));
    writeOperations.add(new InsertOneModel<Document>(new Document("cityId", 1130)
      .append("cityName", "Mumbai")
      .append("countryName", "India")
      .append("continentName", "Asia")
      .append("population", 55)));
    
    writeOperations.add(new UpdateOneModel<Document>(new Document("cityName", "New Delhi"),
      new Document("$set", new Document("status", "High Population"))
    ));
    writeOperations.add(new UpdateManyModel<Document>(new Document("cityName", "London"),
      new Document("$set", new Document("status", "Low Population"))
    ));
    
    writeOperations.add(new DeleteOneModel<Document>(new Document("cityName", "Mexico City")));
    
    writeOperations.add(new ReplaceOneModel<Document>(new Document("cityId", 1124), 
      new Document("cityName", "New York").append("cityName", "United States")
        .append("continentName", "North America")
        .append("population", 28)));
    
    BulkWriteResult bulkWriteResult = collection.bulkWrite(writeOperations);
    System.out.println("bulkWriteResult:- " + bulkWriteResult);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    在这里,我们首先创建了一个writeModel列表,以将所有不同类型的写入操作添加到单个更新列表中。此外,我们在查询中使用了InsertOneModelUpdateOneModelUpdateManyModelDeleteOneModelReplaceOneModel。最后,bulkWrite方法一次执行所有操作。

    5. 结论

    在本文中,我们学习了使用不同类型的写入操作在 MongoDB 中执行批量操作。我们在单个数据库查询中执行文档的插入、更新、删除和替换。另外,我们学习了initializeOrderedBulkOp 在MongoDB中批量更新的用例。

    首先,我们研究了 MongoDB shell 查询中批量操作的用例,然后讨论了相应的 Java 驱动程序代码。

  • 相关阅读:
    申请实用新型专利需要的时间
    机器学习之特征选择
    nrf52832 开发板入手笔记:J-Flash 蓝牙协议栈烧写
    Git中tag的用法及作用
    正则化函数表达是什么意思,一般是怎么用的
    【编程题】【Scratch四级】2022.09 三个数排序
    众和策略:华为汽车概念活跃,圣龙股份斩获12板,华峰超纤涨10%
    排序 算法(第4版)
    【mysql】centos安装mysql8
    【软件设计师21天-考点整理】1)计算机系统构成及硬件基础知识
  • 原文地址:https://blog.csdn.net/wjw465150/article/details/127794456