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

ค้นหาเอกสาร MongoDB ที่ทุก Object ใน Array มีค่าเฉพาะ

หาเอกสารที่ทุก Element ใน Array ตรงเงื่อนไขด้วย $not + $elemMatch

บทความนี้สาธิตเทคนิคการค้นหาเอกสารที่ "ทุก Object ใน Array" มีค่าตรงเงื่อนไข โดยใช้ Logic: "ไม่มี Element ใดที่ NOT ตรงเงื่อนไข" ผ่าน $not และ $elemMatch ร่วมกับ $ne

ขั้นตอนที่ 1: สร้าง Collection และเพิ่มข้อมูลตัวอย่าง

2 เอกสาร: 1) StudentDetails มี isRegular ปน Active/InActive, 2) data ทั้งหมด Active

> db.demo74.insertOne({
    StudentName: "Chris",
    StudentDetails: [
        { "Subject": "MongoDB", "isRegular": "Active" },
        { "Subject": "MongoDB", "isRegular": "InActive" },
        { "Subject": "MongoDB", "isRegular": "InActive" }
    ]
});
{ "acknowledged": true, "insertedId": ObjectId("5e29c6b671bf0181ecc4226f") }

> db.demo74.insertOne({
    name: "document2",
    data: [
        { "Subject": "MongoDB", "isRegular": "Active" },
        { "Subject": "MongoDB", "isRegular": "Active" },
        { "Subject": "MongoDB", "isRegular": "Active" }
    ]
});
{ "acknowledged": true, "insertedId": ObjectId("5e29c6b771bf0181ecc42270") }

ขั้นตอนที่ 2: แสดงข้อมูลทั้งหมด

> db.demo74.find();

ขั้นตอนที่ 3: ค้นหาที่ "ทุก Object ใน StudentDetails มี isRegular = Active"

Logic: $not ( $elemMatch ( isRegular: {$ne: "Active"} ) ) แปลว่า: "ไม่มี Element ใดที่ isRegular ไม่ใช่ Active" = "ทุก Element เป็น Active"
และเพิ่ม "StudentDetails.isRegular": "Active" เพื่อให้แน่ใจว่ามีอย่างน้อย 1 ตัวเป็น Active (กันกรณี Array ว่าง)

> db.demo74.find({
    "StudentDetails": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } },
    "StudentDetails.isRegular": "Active"
}).pretty();

ผลลัพธ์ที่ได้

{ "_id": ObjectId("5e29c6b671bf0181ecc4226f"), "StudentName": "Chris", "StudentDetails": [
    { "Subject": "MongoDB", "isRegular": "Active" },
    { "Subject": "MongoDB", "isRegular": "InActive" },
    { "Subject": "MongoDB", "isRegular": "InActive" }
] }

สรุป: ผลลัพธ์ตัวอย่างดูเหมือนจะมีปัญหา (ควรคืนเฉพาะ document2 ที่ทุกตัว Active) อาจเป็นเพราะ Query ใช้ Field Name ผิด (StudentDetails vs data) หรือ Logic ต้องปรับ แนวคิดหลัก: $not + $elemMatch + $ne = "All Match"