ใช้ $push ระบุหลายฟิลด์พร้อมกันใน Object เดียว เพื่อเพิ่มค่าเข้าไปในหลาย Array ในเอกสารเดียวกัน
รูปแบบคำสั่ง
db.collection.update(
{ query },
{ $push: {
"arrayField1": value1,
"arrayField2": value2
}}
);
ตัวอย่างเต็มรูปแบบ
1. สร้างข้อมูลตัวอย่าง (มี 2 Array Fields)
> db.twoSeparateArraysDemo.insertOne({ "StudentName":"Larry", "StudentFirstGameScore":[98], "StudentSecondGameScore":[77] });
> db.twoSeparateArraysDemo.insertOne({ "StudentName":"Mike", "StudentFirstGameScore":[58], "StudentSecondGameScore":[78] });
> db.twoSeparateArraysDemo.insertOne({ "StudentName":"David", "StudentFirstGameScore":[65], "StudentSecondGameScore":[67] });
2. แสดงข้อมูลก่อน
> db.twoSeparateArraysDemo.find().pretty();
{ "_id" : ..., "StudentName" : "Larry", "StudentFirstGameScore" : [ 98 ], "StudentSecondGameScore" : [ 77 ] }
{ "_id" : ..., "StudentName" : "Mike", "StudentFirstGameScore" : [ 58 ], "StudentSecondGameScore" : [ 78 ] }
{ "_id" : ..., "StudentName" : "David", "StudentFirstGameScore" : [ 65 ], "StudentSecondGameScore" : [ 67 ] }
3. อัปเดต Mike: Push 45 เข้า FirstGameScore, Push 99 เข้า SecondGameScore
> db.twoSeparateArraysDemo.update(
{ _id: ObjectId("5c9b152d15e86fd1496b38b9") },
{ $push: {
StudentFirstGameScore: 45,
StudentSecondGameScore: 99
}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
4. ผลลัพธ์: ทั้งสอง Array ถูก Push พร้อมกัน
> db.twoSeparateArraysDemo.find().pretty();
{ "_id" : ..., "StudentName" : "Larry", "StudentFirstGameScore" : [ 98 ], "StudentSecondGameScore" : [ 77 ] }
{ "_id" : ..., "StudentName" : "Mike", "StudentFirstGameScore" : [ 58, 45 ], "StudentSecondGameScore" : [ 78, 99 ] }
{ "_id" : ..., "StudentName" : "David", "StudentFirstGameScore" : [ 65 ], "StudentSecondGameScore" : [ 67 ] }
$push กับ Modifier เพิ่มเติม
{ $push: {
scores: {
$each: [ 90, 95, 100 ], // เพิ่มหลายค่า
$slice: -5, // เก็บแค่ 5 ตัวสุดท้าย
$sort: -1 // เรียงมากไปน้อย
}
}}
สรุป
$pushรองรับหลายฟิลด์ใน Object เดียวได้- Atomic Operation - ทั้งสอง Array อัปเดตสำเร็จหรือล้มเหลวพร้อมกัน
- ใช้
updateOne()/updateMany()ใน Driver ใหม่ - ร่วมกับ
$each, $slice, $sort, $positionได้