<返回更多

MongoDB使用Bulk批量更新操作

2023-03-20  今日头条  JAVA微学堂
加入收藏

 

概述

MongoDB支持执行批量更新和插入操作,允许在一次操作中插入或检索多个文档。通过使用Batch接口,减少客户端和数据库之间的调用次数,可以显著提高数据库访问性能。

本文将演示如何使用MongoDB Shell和JAVA代码两种方式实现文档的批量更新。

数据库初始化

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

mongo --host localhost --port 27017

建立一个数据库testDb和一个populations集合:

use testDb;
db.createCollection(populations);

使用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
}]);

执行上述insertMany查询将返回以下文档:

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("623575049d55d4e137e477f6"),
        ObjectId("623575049d55d4e137e477f7"),
        ObjectId("623575049d55d4e137e477f8"),
        ObjectId("623575049d55d4e137e477f9")
    ]
}

使用MongoDB Shell查询

MongoDB的批量操作生成器用于为单个集合批量构建写操作列表,可以使用insert、update、replace和remove等方法执行不同类型的操作:

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

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

{
    "acknowledged" : true,
    "deletedCount" : 1,
    "insertedCount" : 2,
    "matchedCount" : 3,
    "upsertedCount" : 0,
    "insertedIds" : 
        {
            "0" : ObjectId("623575f89d55d4e137e477f9"),
            "1" : ObjectId("623575f89d55d4e137e477fa")
        },
    "upsertedIds" : {}
}

使用Java进行批量操作

首先创建一个MongoClient连接:

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("testDb");
MongoCollection<Document> collection = database.getCollection("populations");

使用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);

首先创建了一个writeModel列表,将所有不同类型的写操作添加到一个更新列表中。此外,我们在查询中使用了InsertOneModel、UpdateOneModel、UpdateManyModel、DeleteOneModel和ReplaceOneModel。最后,bulkWrite方法一次执行了所有的操作。

结论

MongoDB的Bulk批量操作详细资料可以参考:
https://www.mongodb.com/docs/manual/core/bulk-write-operations/

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>