Bạn có thể sử dụng toán tử $ push cho việc này. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Larry","StudentFirstGameScore":[98],"StudentSecondGameScore":[77]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b152815e86fd1496b38b8")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Mike","StudentFirstGameScore":[58],"StudentSecondGameScore":[78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b152d15e86fd1496b38b9")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"David","StudentFirstGameScore":[65],"StudentSecondGameScore":[67]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b153315e86fd1496b38ba")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.twoSeparateArraysDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9b152815e86fd1496b38b8"),
"StudentName" : "Larry",
"StudentFirstGameScore" : [
98
],
"StudentSecondGameScore" : [
77
]
}
{
"_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
"StudentName" : "Mike",
"StudentFirstGameScore" : [
58
],
"StudentSecondGameScore" : [
78
]
}
{
"_id" : ObjectId("5c9b153315e86fd1496b38ba"),
"StudentName" : "David",
"StudentFirstGameScore" : [
65
],
"StudentSecondGameScore" : [
67
]
} Sau đây là truy vấn để đẩy hai mảng riêng biệt trong một lệnh gọi cập nhật trong MongoDB
> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Hãy để chúng tôi kiểm tra xem giá trị có được đẩy vào hai mảng riêng biệt hay không
> db.twoSeparateArraysDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9b152815e86fd1496b38b8"),
"StudentName" : "Larry",
"StudentFirstGameScore" : [
98
],
"StudentSecondGameScore" : [
77
]
}
{
"_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
"StudentName" : "Mike",
"StudentFirstGameScore" : [
58,
45
],
"StudentSecondGameScore" : [
78,
99
]
}
{
"_id" : ObjectId("5c9b153315e86fd1496b38ba"),
"StudentName" : "David",
"StudentFirstGameScore" : [
65
],
"StudentSecondGameScore" : [
67
]
}