MongoDB-এ অ্যারেতে থাকা সব এলিমেন্টের নির্দিষ্ট ফিল্ডের মান নির্দিষ্ট ভ্যালু (যেমন ১২০) কিনা তা যাচাই করতে $not + $elemMatch + $ne কম্বিনেশন ব্যবহার করুন।
উদাহরণ
নেস্টেড অবজেক্ট অ্যারে সহ দুটি ডকুমেন্ট তৈরি করুন:
> db.findDocumentsDemo.insertOne({
_id: 101,
"ProductDetails": [ { "ProductValue": 100 }, { "ProductValue": 120 } ]
});
{ "acknowledged" : true, "insertedId" : 101 }
> db.findDocumentsDemo.insertOne({
_id: 102,
"ProductDetails": [ { "ProductValue": 120 }, { "ProductValue": 120 }, { "ProductValue": 120 } ]
});
{ "acknowledged" : true, "insertedId" : 102 }
সকল ডকুমেন্ট দেখুন:
> db.findDocumentsDemo.find().pretty();
আউটপুট:
{ "_id" : 101, "ProductDetails" : [ { "ProductValue" : 100 }, { "ProductValue" : 120 } ] }
{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }
সকল ProductValue = 120 থাকা ডকুমেন্ট বের করা
> db.findDocumentsDemo.find({
"ProductDetails.ProductValue": { $exists: true },
"ProductDetails": {
$not: {
$elemMatch: {
"ProductValue": { $ne: 120 }
}
}
}
});
আউটপুট:
{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }
ব্যাখ্যা:
$elemMatch: { ProductValue: { $ne: 120 } }— অ্যারেতে কোনো একটি এলিমেন্টের ProductValue ১২০ নয় কিনা চেক করে।$not— সেটি নেগেট করে: অর্থাৎ কোনো এলিমেন্টও ১২০ নয় নেই → সকল এলিমেন্ট ১২০।ProductDetails.ProductValue: { $exists: true }— অ্যারে খালি না হলে নিশ্চিত করে (ঐচ্ছিক)।
লজিক: "১২০ নয় এমন এলিমেন্ট নেই" = "সকল এলিমেন্ট ১২০"।
বিকল্প (MongoDB ৩.৬+): $expr + $allElementsTrue
db.findDocumentsDemo.find({
$expr: {
$allElementsTrue: {
$map: {
input: "$ProductDetails",
as: "p",
in: { $eq: ["$$p.ProductValue", 120] }
}
}
}
});
সুপারিশ: আধুনিক ভার্সনে $expr পদ্ধতিটি আরও পঠনীয় এবং মেইনটেইনযোগ্য।