MongoDB में किसी नेस्टेड फील्ड की मौजूदगी जांचने के लिए डॉट नोटेशन के साथ $exists ऑपरेटर का उपयोग करें।
उदाहरण
नेस्टेड ऑब्जेक्ट वाले दस्तावेज़ बनाएं:
> db.findDocumentContainsSpecificFieldDemo.insertOne({"ProductPrices": {"Product1": 10, "Product2": 50}});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf2385bb64a577be5a2bc14") }
> db.findDocumentContainsSpecificFieldDemo.insertOne({"ProductPrices": {"Product3": 150, "Product7": 100, "Product5": 250}});
{ "acknowledged" : true, "insertedId" : ObjectId("5cf2387eb64a577be5a2bc15") }
दस्तावेज़ देखें:
> db.findDocumentContainsSpecificFieldDemo.find().pretty();
{ "_id" : ObjectId("5cf2385bb64a577be5a2bc14"), "ProductPrices" : { "Product1" : 10, "Product2" : 50 } }
{ "_id" : ObjectId("5cf2387eb64a577be5a2bc15"), "ProductPrices" : { "Product3" : 150, "Product7" : 100, "Product5" : 250 } }
ProductPrices.Product2 फील्ड वाले दस्तावेज़ ढूंढें
> db.findDocumentContainsSpecificFieldDemo.find({"ProductPrices.Product2": {$exists: true}});
आउटपुट:
{ "_id" : ObjectId("5cf2385bb64a577be5a2bc14"), "ProductPrices" : { "Product1" : 10, "Product2" : 50 } }
व्याख्या:
ProductPrices.Product2- डॉट नोटेशन नेस्टेड फील्ड तक पहुंचता है$exists: true- फील्ड मौजूद है (मान null भी हो तो भी)- पहला दस्तावेज़ मेल खाता है क्योंकि Product2 मौजूद है
- दूसरा दस्तावेज़ नहीं क्योंकि Product2 नहीं है
$exists व्यवहार
| दस्तावेज़ | {field: {$exists: true}} | {field: {$exists: false}} |
|---|---|---|
| {a: 1} | मेल | नहीं |
| {a: null} | मेल | नहीं |
| {b: 2} | नहीं | मेल |
| {} | नहीं | मेल |
नोट: $exists: true नल मान वाले फील्ड के लिए भी सही लौटाता है। केवल फील्ड अनुपस्थिति के लिए $exists: false उपयोग करें।