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

Query Sub-element (องค์ประกอบย่อย) ใน MongoDB

ใช้ Positional Operator $ Project เฉพาะ Element ที่ Match ใน Array

เมื่อ Query Array of Objects และต้องการ Return เฉพาะ Element แรกที่ Match ใช้ $ (Positional Projection) ใน Projection Document

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

> db.subElementQueryingDemo.insertOne({
    "ClientName": "Chris",
    "Status": [ { "isMarried": true }, { "isMarried": false } ]
});

คิวรี: หา Client ที่มี Status.isMarried = true และ Project เฉพาะ Element นั้น

> db.subElementQueryingDemo.find(
    { "Status.isMarried": true },
    { ClientName: 1, 'Status.$': 1 }
).pretty();

ผลลัพธ์

{ "_id" : ObjectId("5ccf28c9dceb9a92e6aa1953"),
  "ClientName" : "Chris",
  "Status" : [ { "isMarried" : true } ]  ← มีแค่ Element ที่ Match
}

กฎของ Positional Operator $

  • ใช้ได้ใน Projection เท่านั้น (ไม่ใช่ Query)
  • Return Element แรก ที่ Match Query Condition
  • ใช้ได้ 1 ตัวต่อ Query (ไม่รองรับ Multiple Positional)
  • ต้องมี Field นั้นใน Query Condition (เช่น Status.isMarried)

ขยาย: ใช้ $elemMatch ใน Projection (MongoDB 3.2+)

สำหรับ Match หลายเงื่อนไขใน Element เดียวกัน:

db.collection.find(
    { "items": { $elemMatch: { price: { $gt: 100 }, inStock: true } } },
    { "items.$elemMatch": { price: { $gt: 100 }, inStock: true } }
);

Aggregation Alternative (ยืดหยุ่นกว่า)

db.subElementQueryingDemo.aggregate([
    { $match: { "Status.isMarried": true } },
    { $project: {
        ClientName: 1,
        Status: {
            $filter: {
                input: "$Status",
                cond: { $eq: ["$$this.isMarried", true] }
            }
        }
    }}
]);

ผลลัพธ์ Aggregation

Return ทุก Element ที่ Match (ไม่ใช่แค่ตัวแรก)

{ "ClientName" : "Chris", "Status" : [ { "isMarried" : true } ] }