स्थितीय ($) ऑपरेटर का उपयोग
MongoDB में, किसी सरणी के अंदर नेस्टेड दस्तावेज़ से विशिष्ट फील्ड प्रोजेक्ट करने के लिए स्थितीय ($) ऑपरेटर का उपयोग किया जाता है। यह क्वेरी मानदंड से मेल खाने वाले सरणी के पहले तत्व को प्रोजेक्ट करता है।
उदाहरण: संग्रह और दस्तावेज़ बनाना
> db.projectSpecificFieldDemo.insertOne(
... {
... "UniqueId": 101,
... "StudentDetails" : [
... {"StudentName" : "Chris", "StudentCountryName " : "US"},
... {"StudentName" : "Robert", "StudentCountryName" : "UK"}
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2") }
> db.projectSpecificFieldDemo.insertOne(
... {
... "UniqueId": 102,
... "StudentDetails" : [
... {"StudentName" : "Robert", "StudentCountryName " : "UK"},
... {"StudentName" : "David", "StudentCountryName" : "AUS"}
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5ca27b106304881c5ce84ba3") }
सभी दस्तावेज़ देखना
> db.projectSpecificFieldDemo.find().pretty();
आउटपुट:
{ "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"), "UniqueId" : 101, "StudentDetails" : [ { "StudentName" : "Chris", "StudentCountryName " : "US" }, { "StudentName" : "Robert", "StudentCountryName" : "UK" } ] }
{ "_id" : ObjectId("5ca27b106304881c5ce84ba3"), "UniqueId" : 102, "StudentDetails" : [ { "StudentName" : "Robert", "StudentCountryName " : "UK" }, { "StudentName" : "David", "StudentCountryName" : "AUS" } ] }
स्थितीय ऑपरेटर के साथ प्रोजेक्शन
UniqueId 101 वाले दस्तावेज़ में, StudentName "Chris" वाले सरणी तत्व को प्रोजेक्ट करें:
> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();
आउटपुट:
{ "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"), "StudentDetails" : [ { "StudentName" : "Chris", "StudentCountryName " : "US" } ] }
महत्वपूर्ण: स्थितीय ऑपरेटर $ केवल क्वेरी मानदंड से मेल खाने वाले **पहले** सरणी तत्व को प्रोजेक्ट करता है। यदि आपको सभी मेल खाने वाले तत्वों की आवश्यकता है, तो एग्रीगेशन पाइपलाइन में $filter या $map का उपयोग करें।