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 } ] }
व्याख्या:
ProductDetails.ProductValue: {$exists: true}- फील्ड मौजूद है (खाली सरणी बाहर)$elemMatch: {ProductValue: {$ne: 120}}- 120 नहीं वाला तत्व ढूंढता है$not- इसे उलट देता है: कोई भी तत्व 120 नहीं है- परिणाम: सभी तत्व 120 हैं
तर्क: "सभी तत्व 120 हैं" = "कोई तत्व 120 नहीं है ऐसा नहीं है" = NOT (EXISTS element != 120)
सरल सरणी (ऑब्जेक्ट नहीं) के लिए
// सरणी: [120, 120, 120]
db.collection.find({
Values: {$not: {$elemMatch: {$ne: 120}}}
})
MongoDB 3.6+ में $expr विकल्प:
db.collection.find({
$expr: {$eq: [{$size: "$Values"}, {$size: {$filter: {input: "$Values", cond: {$eq: ["$$this", 120]}}}}]}
})
यह सरणी आकार और फिल्टर बाद के आकार की तुलना करता है।