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

ค้นหาเอกสารที่ Element แรกใน Array ตรงเงื่อนไขใน MongoDB

บทความนี้สาธิตการใช้ Dot Notation ร่วมกับ Index 0 เพื่อค้นหาเอกสารที่ Element แรก (Index 0) ของ Array มีค่าตรงตามที่ต้องการ

สร้างข้อมูลตัวอย่าง

> db.matchingFirstItemInTheArrayDemo.insertOne(
  { "ClientDetails": [ { "ClientName": "Larry", "ClientAge": 28 } ] }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a5d26d78f205348bc636") }

> db.matchingFirstItemInTheArrayDemo.insertOne(
  { "ClientDetails": [ { "ClientName": "Chris", "ClientAge": 56 } ] }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a5f56d78f205348bc637") }

> db.matchingFirstItemInTheArrayDemo.insertOne(
  { "ClientDetails": [ { "ClientName": "Robert", "ClientAge": 46 } ] }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7a6076d78f205348bc638") }

แสดงข้อมูลทั้งหมด

> db.matchingFirstItemInTheArrayDemo.find().pretty();
{
  "_id" : ObjectId("5cd7a5d26d78f205348bc636"),
  "ClientDetails" : [ { "ClientName" : "Larry", "ClientAge" : 28 } ]
}
{
  "_id" : ObjectId("5cd7a5f56d78f205348bc637"),
  "ClientDetails" : [ { "ClientName" : "Chris", "ClientAge" : 56 } ]
}
{
  "_id" : ObjectId("5cd7a6076d78f205348bc638"),
  "ClientDetails" : [ { "ClientName" : "Robert", "ClientAge" : 46 } ]
}

ค้นหาเอกสารที่ Element แรก (Index 0) มี ClientName = "Chris"

> db.matchingFirstItemInTheArrayDemo.find({"ClientDetails.0.ClientName":"Chris"});

ผลลัพธ์

{ "_id" : ObjectId("5cd7a5f56d78f205348bc637"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientAge" : 56 } ] }

คำอธิบาย Dot Notation กับ Array Index

  • ArrayField.0.FieldName - เข้าถึง FieldName ของ Element ตัวแรก (Index 0)
  • ArrayField.1.FieldName - Element ตัวที่ 2 (Index 1)
  • ArrayField.-1.FieldName - ไม่รองรับ ใน MongoDB (ต้องใช้ Aggregation $arrayElemAt)

ตัวอย่างเพิ่มเติม: ค้นหาตาม Index อื่น

// หา Document ที่ Element ตัวที่ 3 (Index 2) มี Status = "active"
db.collection.find({ "items.2.status": "active" });

// หา Document ที่ Element แรกมี Priority > 5
db.collection.find({ "tasks.0.priority": { $gt: 5 } });

กรณี Array ว่าง หรือไม่มี Element ตรง Index

Query จะไม่คืน Document นั้น (เพราะไม่มี Field ที่ Match)

เทคนิคขั้นสูง: ใช้ Aggregation สำหรับ Last Element

// หา Document ที่ Element สุดท้ายมีค่าเฉพาะ
db.collection.aggregate([
  { $project: {
    lastItem: { $arrayElemAt: ["$items", -1] },
    doc: "$$ROOT"
  }},
  { $match: { "lastItem.status": "completed" } },
  { $replaceRoot: { newRoot: "$doc" } }
]);