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

MongoDB: ใช้ $concatArrays ใน $project กับ Multi-array Field

ใช้ $concatArrays ร่วม $reduce ใน $project เพื่อรวม multi-dimensional array (อาร์เรย์ของอาร์เรย์) ให้กลายเป็นอาร์เรย์แบน (flatten) สร้างคอลเลกชันตัวอย่าง:

> db.demo338.insertOne({"Name":"Chris","Marks1":[ [56,67,45],[67,89,90,91]]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5299baf8647eb59e56209f") }

แสดงข้อมูล:

> db.demo338.find().pretty();

คิวรี flatten อาร์เรย์ Marks1:

> db.demo338.aggregate([
  { "$project": {
    "Marks": {
      "$reduce": {
        "input": "$Marks1",
        "initialValue": [],
        "in": { "$concatArrays": ["$$this", "$$value"] }
      }
    }
  }}
])

ผลลัพธ์:

{ "_id" : ObjectId("5e5299baf8647eb59e56209f"), "Marks" : [ 67, 89, 90, 91, 56, 67, 45 ] }

คำอธิบาย

  • $reduce: วนลูปผ่านแต่ละ sub-array ใน Marks1
  • initialValue: []: เริ่มต้นด้วยอาร์เรย์ว่าง
  • in: { $concatArrays: ["$$this", "$$value"] }: รวม sub-array ปัจจุบัน ($$this) กับผลสะสม ($$value)
  • ลำดับ: sub-array ตัวหลังจะอยู่หน้า (เพราะ concat this + value)

วิธีง่ายกว่า (MongoDB 4.4+)

ใช้ $reduce ร่วม $concatArrays โดยตรง หรือใช้ $function สำหรับ logic ที่ซับซ้อนกว่า ใน MongoDB 5.0+ มี $flatten operator (แค่ proposal ยังไม่ release อย่างเป็นทางการ)