Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

การสร้าง Array เดียวจากหลาย Array ใน MongoDB ด้วย $unwind

เมื่อต้องการรวมหลาย Array ให้กลายเป็น Array เดียว (Flatten) ใน MongoDB สามารถใช้ Stage $unwind ใน Aggregation Pipeline ได้ เนื้อหานี้สาธิตวิธีการแยก Element ใน Array Section ออกเป็นเอกสารแยกต่างหาก

ตัวอย่างข้อมูลทดสอบ

สร้าง Collection demo289 มีเอกสาร 2 รายการ:

> db.demo289.insertOne({"Section":["A","B","E"],"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4c06fcf49383b52759cbc3") }

> db.demo289.insertOne({"Section":["C","D","B"],"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4c070af49383b52759cbc4") }

แสดงข้อมูลเดิม

> db.demo289.find().pretty();
{
    "_id" : ObjectId("5e4c06fcf49383b52759cbc3"),
    "Section" : [ "A", "B", "E" ],
    "Name" : "Chris"
}
{
    "_id" : ObjectId("5e4c070af49383b52759cbc4"),
    "Section" : [ "C", "D", "B" ],
    "Name" : "David"
}

Query ใช้ $unwind

> db.demo289.aggregate({ $unwind : "$Section" } );

ผลลัพธ์หลัง Unwind

แต่ละ Element ใน Array Section จะกลายเป็นเอกสารแยกต่างหาก พร้อมคงค่า Name ไว้:

{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "A", "Name" : "Chris" }
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "B", "Name" : "Chris" }
{ "_id" : ObjectId("5e4c06fcf49383b52759cbc3"), "Section" : "E", "Name" : "Chris" }
{ "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "C", "Name" : "David" }
{ "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "D", "Name" : "David" }
{ "_id" : ObjectId("5e4c070af49383b52759cbc4"), "Section" : "B", "Name" : "David" }

การใช้งานเพิ่มเติม

  • สามารถเพิ่ม preserveNullAndEmptyArrays: true เพื่อรักษาเอกสารที่ Array ว่างหรือ Null
  • รวมกับ $group ได้เพื่อนับจำนวนหรือทำการคำนวณอื่นๆ
  • เหมาะสำหรับการวิเคราะห์ข้อมูลใน Array แบบรายรายการ