MongoDB में शीर्ष N पंक्तियों पर क्वेरी करने के लिए, आप समग्र ढांचे का उपयोग कर सकते हैं। आइए दस्तावेजों के साथ एक संग्रह बनाएं
> db.topNRowsDemo.insertOne({"StudentName":"Larry","Score":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26eee6304881c5ce84b91")
}
> db.topNRowsDemo.insertOne({"StudentName":"Chris","Score":45});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26ef66304881c5ce84b92")
}
> db.topNRowsDemo.insertOne({"StudentName":"Mike","Score":65});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26efe6304881c5ce84b93")
}
> db.topNRowsDemo.insertOne({"StudentName":"Adam","Score":55});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26f066304881c5ce84b94")
}
> db.topNRowsDemo.insertOne({"StudentName":"John","Score":86});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca26f0f6304881c5ce84b95")
} खोज () विधि की मदद से संग्रह से सभी दस्तावेजों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है
> db.topNRowsDemo.find().pretty();
यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : ObjectId("5ca26eee6304881c5ce84b91"),
"StudentName" : "Larry",
"Score" : 78
}
{
"_id" : ObjectId("5ca26ef66304881c5ce84b92"),
"StudentName" : "Chris",
"Score" : 45
}
{
"_id" : ObjectId("5ca26efe6304881c5ce84b93"),
"StudentName" : "Mike",
"Score" : 65
}
{
"_id" : ObjectId("5ca26f066304881c5ce84b94"),
"StudentName" : "Adam",
"Score" : 55
}
{
"_id" : ObjectId("5ca26f0f6304881c5ce84b95"),
"StudentName" : "John",
"Score" : 86
} यहां बताया गया है कि आप MongoDB में शीर्ष N पंक्तियों पर कैसे क्वेरी कर सकते हैं
> db.topNRowsDemo.aggregate([
... {$sort: {StudentName: 1}},
... {$limit: 5},
... {$match: {Score: {$gt: 65}}}
... ]).pretty(); यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : ObjectId("5ca26f0f6304881c5ce84b95"),
"StudentName" : "John",
"Score" : 86
}
{
"_id" : ObjectId("5ca26eee6304881c5ce84b91"),
"StudentName" : "Larry",
"Score" : 78
}