คุณสามารถใช้ตัวดำเนินการ $push สำหรับสิ่งนี้ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน
>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")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()
> db.twoSeparateArraysDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_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
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อผลักสองอาร์เรย์แยกกันในการเรียกอัปเดตครั้งเดียวใน MongoDB
> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) ให้เราตรวจสอบค่าว่าถูกผลักออกเป็นสองอาร์เรย์แยกกันหรือไม่
> db.twoSeparateArraysDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_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
]
}