1. Overview
1.概述
In this tutorial, we’ll look at performing bulk updates and insert operations in MongoDB. Additionally, MongoDB provides API calls that allow inserting or retrieving multiple documents in a single operation. MongoDB uses the Array or Batch interfaces which greatly improve database performance by reducing the number of calls between the client and the database.
在本教程中,我们将了解在MongoDB中执行批量更新和插入操作。此外,MongoDB 还提供了 API 调用,允许在一次操作中插入或检索多个文档。MongoDB 使用 Array 或 Batch 接口,通过减少客户端和数据库之间的调用次数,大大提升了数据库性能。
In this tutorial, we’ll look at both the solutions using MongoDB Shell and Java driver code.
在本教程中,我们将看一下使用MongoDB Shell和Java驱动代码的两种解决方案。
Let’s dive into implementing the bulk updating of documents in MongoDB.
让我们深入了解在MongoDB中实现文档的批量更新。
2. Database Initialization
2.数据库初始化
First of all, we need to connect to the mongo shell:
首先,我们需要连接到mongo shell。
mongo --host localhost --port 27017
Now, set up a database baeldung and a sample collection populations:
现在,建立一个数据库baeldung和一个样本收集populations。
use baeldung;
db.createCollection(populations);
Let’s add some sample data into the collection populations using insertMany method:
让我们使用insertMany方法向集合populations添加一些样本数据。
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
}]);
The above insertMany query will return the following document:
上述insertMany查询将返回以下文件。
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("623575049d55d4e137e477f6"),
ObjectId("623575049d55d4e137e477f7"),
ObjectId("623575049d55d4e137e477f8"),
ObjectId("623575049d55d4e137e477f9")
]
}
Here, we inserted four documents in the above query to perform all the types of write bulk operations in MongoDB.
在这里,我们在上述查询中插入了四个文档,以在MongoDB中执行所有类型的批量写入操作。
The database baeldung has been created successfully, and all the required data is also inserted into the collection populations, so we’re ready to perform the bulk update.
数据库baeldung已经成功创建,所有需要的数据也被插入到集合populations中,所以我们准备执行批量更新。
3. Using MongoDB Shell Query
3.使用MongoDB外壳查询
The bulk operations builder of MongoDB is used to construct a list of write operations in bulk for a single collection. We can initialize bulk operations in 2 different ways. The method initializeOrderedBulkOp is used to perform bulk operations in the ordered list of write operations. One of the drawbacks of the initializeOrderedBulkOp is that if an error occurs while processing any write operations, MongoDB will return without processing the remaining write operations in the list.
MongoDB的批量操作生成器是用来为一个集合批量构建一个写操作列表的。我们可以通过2种不同的方式来初始化批量操作。方法initializeOrderedBulkOp用于在写操作的有序列表中进行批量操作。initializeOrderedBulkOp的一个缺点是,如果在处理任何写操作时发生错误,MongoDB将返回而不处理列表中的剩余写操作。
We can use insert, update, replace and remove methods to perform different types of operations in a single DB call. As an illustration, let’s look into the bulk write operation query using the MongoDB shell:
我们可以使用插入、更新、替换和删除方法,在一次DB调用中执行不同类型的操作。作为一个例子,我们来看看使用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
}
}
}
]);
The above bulkWrite query will return the following document:
上述bulkWrite查询将返回以下文件。
{
"acknowledged" : true,
"deletedCount" : 1,
"insertedCount" : 2,
"matchedCount" : 3,
"upsertedCount" : 0,
"insertedIds" :
{
"0" : ObjectId("623575f89d55d4e137e477f9"),
"1" : ObjectId("623575f89d55d4e137e477fa")
},
"upsertedIds" : {}
}
Here, in the above query, we performed all the types of write operations, i.e., insertOne, updateOne, deleteOne, replaceOne.
在这里,在上述查询中,我们执行了所有类型的写操作,即insertOne, updateOne, deleteOne, replaceOne。
First, we used insertOne method to insert a new document into the collection. Secondly, we used updateOne to update the document of cityName “New Delhi”. Later, we used the deleteOne method to delete a document from the collection based on the filter. Finally, we used replaceOne to replace a complete document with filter cityName “New York”.
首先,我们使用insertOne方法在集合中插入一个新的文档。其次,我们使用updateOne来更新cityName“New Delhi “的文档。后来,我们使用deleteOne方法,根据过滤器从集合中删除一个文档。最后,我们使用replaceOne来替换一个完整的带有过滤器cityName“New York “的文档。
4. Using Java Driver
4.使用Java驱动
We have discussed the MongoDB shell query to perform the bulk write operations. Before creating the bulk write operation, let’s first create a MongoClient connection with the collection populations of the database baeldung:
我们已经讨论了MongoDB shell查询来执行批量写入操作。在创建批量写入操作之前,让我们首先创建一个MongoClient连接,与数据库baeldung的集合populations进行连接。
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("populations");
Here, we created the connection with the MongoDB server, running on default port 27017. Let’s now implement the same bulk operations using the Java code:
在这里,我们创建了与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);
Here, we first created a list of writeModel to add all the different types of write operations into a single update list. Furthermore, we used InsertOneModel, UpdateOneModel, UpdateManyModel, DeleteOneModel, and ReplaceOneModel in our query. Finally, the bulkWrite method executed all the operations at once.
在这里,我们首先创建了一个writeModel的列表,将所有不同类型的写操作添加到一个更新列表中。此外,我们在查询中使用了InsertOneModel, UpdateOneModel, UpdateManyModel, DeleteOneModel, 和ReplaceOneModel。最后,bulkWrite方法一次性执行所有的操作。
5. Conclusion
5.总结
In this article, we have learned to perform bulk operations in MongoDB using different kinds of write operations. We performed the insertion, updating, deletion, and replacement of documents all in a single DB query. In addition, we learned the use cases of initializeOrderedBulkOp into the bulk update in MongoDB.
在这篇文章中,我们已经学会了在MongoDB中使用不同种类的写操作来执行批量操作。我们在一次DB查询中完成了文档的插入、更新、删除和替换。此外,我们还学习了initializeOrderedBulkOp在MongoDB中批量更新的使用案例。
At first, we looked into the use cases of the bulk operations in MongoDB shell query, and then we discussed the corresponding Java driver code.
首先,我们研究了MongoDB shell查询中批量操作的用例,然后我们讨论了相应的Java驱动代码。
The example of all the cases can be found over on GitHub.
所有案例的例子都可以在GitHub上找到over。