1. Overview
1.概述
In this tutorial, we’ll introduce how to insert documents into an array in MongoDB. Additionally, we’ll see various applications of $push and $addToset operators to add values into an array.
在本教程中,我们将介绍如何在MongoDB中向数组插入文档。此外,我们将看到 $push 和 $addToset 操作符的各种应用,以将值添加到数组中。
First, we’ll create a sample database, a collection, and insert dummy data into it. Further, we’ll look into a few basic examples to update a document using the $push operator. Later, we’ll also discuss the various use cases of $push and $addtoSet operators.
首先,我们将创建一个样本数据库,一个集合,并向其中插入假数据。此外,我们将研究几个基本的例子,使用$push操作符更新一个文档。之后,我们还将讨论$push和$addtoSet操作符的各种使用情况。
Let’s deep dive into the various methods to insert documents into an array in MongoDB.
让我们深入了解在MongoDB中向数组插入文档的各种方法。
2. Database Initialisation
2.数据库初始化
First of all, let’s set up a new database baeldung and a sample collection, orders:
首先,让我们建立一个新的数据库baeldung和一个样本集,orders。
use baeldung;
db.createCollection(orders);
Let’s now add a few documents into the collection by using the insertMany method:
现在让我们通过使用insertMany方法在集合中添加一些文档。
db.orders.insertMany([
{
"customerId": 1023,
"orderTimestamp": NumberLong("1646460073000"),
"shippingDestination": "336, Street No.1 Pawai Mumbai",
"purchaseOrder": 1000,
"contactNumber":"9898987676",
"items": [
{
"itemName": "BERGER",
"quantity": 1,
"price": 500
},
{
"itemName": "VEG PIZZA",
"quantity": 1,
"price": 800
}
]
},
{
"customerId": 1027,
"orderTimestamp": NumberLong("1646460087000"),
"shippingDestination": "445, Street No.2 Pawai Mumbai",
"purchaseOrder": 2000,
"contactNumber":"9898987676",
"items": [
{
"itemName": "BERGER",
"quantity": 1,
"price": 500
},
{
"itemName": "NON-VEG PIZZA",
"quantity": 1,
"price": 1200
}
]
}
]);
In case of successful insertion, the above command will print a JSON similar to the one shown below:
在插入成功的情况下,上述命令将打印一个类似于下图的JSON。
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("622300cc85e943405d04b567"),
ObjectId("622300cc85e943405d04b568")
]
}
Till now, we have successfully set up the database and collection. We’ll use this database and collection for all the examples.
到现在为止,我们已经成功地建立了数据库和集合。我们将在所有的例子中使用这个数据库和集合。
3. Push Operation Using Mongo Query
3.使用Mongo查询的推送操作
MongoDB provides various types of array operators to update the arrays in MongoDB documents. The $push operator in MongoDB appends the value at the end of the array. Depending upon the type of query, we can use the $push operator with methods like updateOne, updateMany, findAndModify, etc.
MongoDB提供了各种类型的数组操作符来更新MongoDB文档中的数组。MongoDB中的$push操作符将值追加到数组的末尾。根据查询的类型,我们可以将$push操作符与updateOne、updateMany、findAndModify等方法一起使用。
Let’s now look into the shell query using the $push operator:
现在我们来看看使用$push操作符的shell查询。
db.orders.updateOne(
{
"customerId": 1023
},
{
$push: {
"items":{
"itemName": "PIZZA MANIA",
"quantity": 1,
"price": 800
}
}
});
The above query will return the following document:
上述查询将返回以下文件。
{
"acknowledged":true,
"matchedCount":1,
"modifiedCount":1
}
Let’s now check the document with customerId 1023. Here, we can see that the new item is inserted at the end of the list “items“:
现在让我们检查一下带有customerId 1023的文档。在这里,我们可以看到,新的项目被插入到列表”items“的最后。
{
"customerId" : 1023,
"orderTimestamp" : NumberLong("1646460073000"),
"shippingDestination" : "336, Street No.1 Pawai Mumbai",
"purchaseOrder" : 1000,
"contactNumber" : "9898987676",
"items" : [
{
"itemName" : "BERGER",
"quantity" : 1,
"price" : 500
},
{
"itemName" : "VEG PIZZA",
"quantity" : 1,
"price" : 800
},
{
"itemName" : "PIZZA MANIA",
"quantity" : 1,
"price" : 800
}
]
}
4. Push Operation Using Java Driver Code
4.使用Java驱动代码的推送操作
Till now, we have discussed the MongoDB shell query to push the document into an array. Let’s now implement the push update query using the Java code.
到现在为止,我们已经讨论了MongoDB的shell查询,将文档推送到一个数组中。现在让我们用Java代码来实现推送更新查询。
Before performing the update operation, let’s first connect to the orders collection in the baeldung database:
在执行更新操作之前,让我们首先连接到baeldung数据库的orders集合。
mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("orders");
Here, in this case, we are connecting to MongoDB which is running at default port 27017 on localhost.
在这里,在这种情况下,我们正在连接到MongoDB,它运行在本地主机的默认端口27017。
4.1. Using the DBObject
4.1.使用DBObject
MongoDB Java driver provides support of both the DBObject and BSON document. Here, the DBObject is part of the MongoDB legacy driver, but it is deprecated in the newer version of the MongoDB.
MongoDB Java 驱动程序提供对DBObject和BSON文档的支持。这里,DBObject是 MongoDB 传统驱动程序的一部分,但在较新版本的 MongoDB 中已被弃用。
Let’s now look into the Java driver code to insert new values into the array:
现在让我们来看看在数组中插入新值的Java驱动代码。
DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA")
.append("quantity", 1)
.append("price", 800));
BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$push", listItem);
UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
In the above query, we first created the item document using the BasicDBObject. On the basis of searchQuery, the documents of the collection will be filtered, and the values will be pushed into the array.
在上述查询中,我们首先使用BasicDBObject创建了项目文档。在searchQuery的基础上,集合中的文档将被过滤,其值将被推入数组。
4.2. Using the BSON Document
4.2.使用BSON文件
The BSON Document is the new way to access the MongoDB document in Java that is built with the newer client stack. The org.bson.Document class is less complicated and easier to use.
BSON Document是在Java中访问MongoDB文档的新方式,它是用较新的客户端栈构建的。org.bson.Document类没有那么复杂,更容易使用。
Let’s use the org.bson.Document class to push values into the array “items”:
让我们使用org.bson.Document类来将值推入数组”items”。
Document item = new Document()
.append("itemName1", "PIZZA MANIA")
.append("quantity", 1).append("price", 800);
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
In this case, the implementation of the BSON is similar to the code run using the DBObject, and the updation will also be the same. Here, we used the updateOne method to update only a single document.
在这种情况下,BSON的实现与使用DBObject运行的代码类似,更新也将是一样的。在这里,我们使用updateOne方法,只更新一个文档。
5. Using the addToSet Operator
5.使用addToSet操作符
The $addToSet operator can also be used to push a value in the array. This operator adds values only if that value doesn’t exist in the array. Otherwise, it will just ignore it. Whereas the push operator will push the value as the condition to filter get the match.
$addToSet操作符也可以用来在数组中推送一个值。这个操作符只在该值不存在于数组中的情况下添加值。否则,它将直接忽略它。而推送操作符将推送该值作为条件来过滤获得匹配。
One key point to note is the $addToSet operator doesn’t push the value work in the case of a duplicate item. On the other hand, the $push operator just pushes the value into the array irrespective of any other conditions.
需要注意的一个关键点是,$addToSet操作符在出现重复项的情况下不会推送值。另一方面,$push操作符只是将值推入数组,而不考虑任何其他条件。
5.1. Shell Query Using the addToSet Operator
5.1.使用addToSet操作符的外壳查询
The mongo shell query of the $addToSet operator is similar to the $push operator, but the $addToSet doesn’t insert the duplicate value in the array.
$addToSet操作符的mongo shell查询与$push操作符类似,但$addToSet并不在数组中插入重复的值。
Let’s now check out the MongoDB query to push the values into an array using the $addToset:
现在让我们检查一下MongoDB查询,使用$addToset将值推入数组。
db.orders.updateOne(
{
"customerId": 1023
},
{
$addToSet: {
"items":{
"itemName": "PASTA",
"quantity": 1,
"price": 1000
}
}
});
In this case, the output will be as follows:
在这种情况下,输出将如下。
{
"acknowledged":true,
"matchedCount":1,
"modifiedCount":1
}
In this case, we used the $addToSet operator, and the document will be pushed to array “items” only if it is unique.
在这种情况下,我们使用了$addToSet操作符,只有当文档是唯一的,才会被推送到数组 “items”。
5.2. Java Driver Using the addToSet Operator
5.2.使用addToSet操作符的Java驱动程序
The $addToSet operator provides a different type of array update operation compared to the push operator:
$addToSet操作符与push操作符相比,提供了一种不同类型的数组更新操作。
Document item = new Document()
.append("itemName1", "PIZZA MANIA")
.append("quantity", 1).append("price", 800);
UpdateResult updateResult = collection
.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
System.out.println("updateResult:- " + updateResult);
In the above code, first, we created the document “item“, and on the basis of the customerId filter, the updateOne method will try to push the document “item” into the array “items“.
在上面的代码中,首先,我们创建了文档”item“,根据customerId过滤器,updateOne方法将尝试把文档”item“推入数组”items“。
6. Conclusion
6.结语
In this article, we have learned to push new values into the array using the $push and $addToSet operators. First, we looked into the use of the $push operator in MongoDB shell query, and then we discussed the corresponding Java driver code.
在这篇文章中,我们已经学会了使用$push和$addToSet操作符将新值推入数组。首先,我们研究了$push操作符在MongoDB shell查询中的使用,然后我们讨论了相应的Java驱动代码。
The implementation of all the cases can be found over on GitHub.
所有案例的实现都可以在GitHub上找到over。