MongoDB में सरणी के अंदर ऑब्जेक्ट्स से विशिष्ट फील्ड निकालकर लौटाने के लिए एग्रीगेशन में $project और $arrayElemAt का उपयोग करें।
उदाहरण
सबडॉक्यूमेंट सरणी वाला दस्तावेज़ बनाएं:
> db.returnSpecificFieldDemo.insertOne(
{
"StudentId": 1,
"StudentDetails": [
{"StudentName": "Larry", "StudentAge": 21, "StudentCountryName": "US"},
{"StudentName": "Chris", "StudentAge": 23, "StudentCountryName": "AUS"}
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ce23d3236e8b255a5eee943") }
दस्तावेज़ देखें:
> db.returnSpecificFieldDemo.find().pretty();
{ "_id" : ObjectId("5ce23d3236e8b255a5eee943"), "StudentId" : 1, "StudentDetails" : [ { "StudentName" : "Larry", "StudentAge" : 21, "StudentCountryName" : "US" }, { "StudentName" : "Chris", "StudentAge" : 23, "StudentCountryName" : "AUS" } ] }
दूसरे तत्व (इंडेक्स 1) का StudentCountryName प्राप्त करें
> db.returnSpecificFieldDemo.aggregate([
{$project: {
_id: 0,
StudentId: "$StudentId",
StudentCountryName: {$arrayElemAt: ["$StudentDetails.StudentCountryName", 1]}
}}
]);
आउटपुट:
{ "StudentId" : 1, "StudentCountryName" : "AUS" }
व्याख्या:
$StudentDetails.StudentCountryName- सरणी के सभी ऑब्जेक्ट से StudentCountryName निकालकर सरणी बनाता है: ["US", "AUS"]$arrayElemAt: [array, index]- सरणी से इंडेक्स पर तत्व लौटाता है (0-आधारित)1- दूसरा तत्व (AUS)
सभी देशों के नाम सरणी के रूप में प्राप्त करें
db.returnSpecificFieldDemo.aggregate([
{$project: {
_id: 0,
StudentId: 1,
AllCountries: "$StudentDetails.StudentCountryName"
}}
])
{ "StudentId" : 1, "AllCountries" : [ "US", "AUS" ] }
पहले तत्व का पूरा ऑब्जेक्ट प्राप्त करें
db.returnSpecificFieldDemo.aggregate([
{$project: {
_id: 0,
StudentId: 1,
FirstStudent: {$arrayElemAt: ["$StudentDetails", 0]}
}}
])
{ "StudentId" : 1, "FirstStudent" : { "StudentName" : "Larry", "StudentAge" : 21, "StudentCountryName" : "US" } }
उपयोग: नेस्टेड सरणी से विशिष्ट स्थिति का डेटा निकालने, रिपोर्टिंग, UI ड्रॉपडाउन के लिए।