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

คิวรี่ MongoDB คืนค่าฟิลด์เฉพาะจากอาร์เรย์

ใช้ $project ใน Aggregate Framework พร้อม $arrayElemAt เพื่อดึงฟิลด์เฉพาะจากตำแหน่งที่กำหนดในอาร์เรย์ เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.returnSpecificFieldDemo.insertOne(
  {
    "StudentId":1,
    "StudentDetails": [
      { "StudentName":"Larry", "StudentAge":21, "StudentCountryName":"US" },
      { "StudentName":"Chris", "StudentAge":23, "StudentCountryName":"AUS" }
    ]
  }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ce23d3236e8b255a5eee943") }

แสดงเอกสาร:

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

คิวรี่ Aggregate ดึง StudentCountryName ของรายการที่ 2 (index 1) ในอาร์เรย์:

> db.returnSpecificFieldDemo.aggregate([
  {$project:{
    _id:0,
    StudentId:'$StudentId',
    StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName', 1] }
  }}
]);

คำอธิบาย:

  • $arrayElemAt: [array, index] - ดึงองค์ประกอบที่ index ที่ระบุ (เริ่มจาก 0)
  • '$StudentDetails.StudentCountryName' - ดึงค่า StudentCountryName จากทุกออบเจกต์ในอาร์เรย์ กลายเป็นอาร์เรย์ ["US", "AUS"]
  • index 1 = รายการที่ 2 = "AUS"

ใช้ index ติดลบได้: -1 = รายการสุดท้าย