दस्तावेज़ों में उप-सरणी से उच्चतम मान प्राप्त करने के लिए, आप एक समग्र ढांचे का उपयोग कर सकते हैं। आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं
> db.findHighestValueDemo.insertOne(
... {
... _id: 10001,
... "StudentDetails": [
... { "StudentName": "Chris", "StudentMathScore": 56},
... { "StudentName": "Robert", "StudentMathScore":47 },
... { "StudentName": "John", "StudentMathScore": 98 }]
... }
... );
{ "acknowledged" : true, "insertedId" : 10001 }
> db.findHighestValueDemo.insertOne(
... {
... _id: 10002,
... "StudentDetails": [
... { "StudentName": "Ramit", "StudentMathScore": 89},
... { "StudentName": "David", "StudentMathScore":76 },
... { "StudentName": "Bob", "StudentMathScore": 97 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 10002 } खोज () विधि की सहायता से संग्रह से सभी दस्तावेज़ों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है
> db.findHighestValueDemo.find().pretty();
यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : 10001,
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentMathScore" : 56
},
{
"StudentName" : "Robert",
"StudentMathScore" : 47
},
{
"StudentName" : "John",
"StudentMathScore" : 98
}
]
}
{
"_id" : 10002,
"StudentDetails" : [
{
"StudentName" : "Ramit",
"StudentMathScore" : 89
},
{
"StudentName" : "David",
"StudentMathScore" : 76
},
{
"StudentName" : "Bob",
"StudentMathScore" : 97
}
]
} दस्तावेज़ों में उप-सरणी से उच्चतम मूल्य खोजने के लिए क्वेरी निम्नलिखित है
> db.findHighestValueDemo.aggregate([
... {$project:{"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}},
... {$unwind:"$StudentDetails"},
... {$sort:{"StudentDetails.StudentMathScore":-1}},
... {$limit:1}
... ]).pretty(); यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : 10001,
"StudentDetails" : {
"StudentName" : "John",
"StudentMathScore" : 98
}
}