MongoDB में सॉर्ट किए गए डेटा के साथ अलग-अलग मान प्राप्त करने के लिए क्वेरी निम्नलिखित है
db.yourCollectionName.distinct("yourFieldName").sort(); आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e3315e86fd1496b38c3")
}
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e3e15e86fd1496b38c4")
}
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e4415e86fd1496b38c5")
}
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":30,"StudentName":"Chris","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e5115e86fd1496b38c6")
}
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e5715e86fd1496b38c7")
}
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e6515e86fd1496b38c8")
}
>db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","Stude
ntAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e6d15e86fd1496b38c9")
} खोज () विधि की सहायता से संग्रह से सभी दस्तावेजों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है;
> db.getDistinctWithSortedDataDemo.find().pretty();
यह निम्नलिखित आउटपुट उत्पन्न करेगा
{
"_id" : ObjectId("5c9b1e3315e86fd1496b38c3"),
"StudentId" : 10,
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9b1e3e15e86fd1496b38c4"),
"StudentId" : 20,
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9b1e4415e86fd1496b38c5"),
"StudentId" : 10,
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9b1e5115e86fd1496b38c6"),
"StudentId" : 30,
"StudentName" : "Chris",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9b1e5715e86fd1496b38c7"),
"StudentId" : 20,
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9b1e6515e86fd1496b38c8"),
"StudentId" : 40,
"StudentName" : "Bob",
"StudentAge" : 20
}
{
"_id" : ObjectId("5c9b1e6d15e86fd1496b38c9"),
"StudentId" : 40,
"StudentName" : "Bob",
"StudentAge" : 20
} "स्टूडेंटनाम" के लिए सॉर्ट किए गए डेटा के साथ अलग-अलग मान प्राप्त करने के लिए क्वेरी निम्नलिखित है
> db.getDistinctWithSortedDataDemo.distinct("StudentName").sort(); यह निम्नलिखित आउटपुट उत्पन्न करेगा
[ "Bob", "Carol", "Chris", "John" ]
स्टूडेंटएज के लिए सॉर्ट किए गए डेटा के साथ अलग-अलग मान प्राप्त करने के लिए क्वेरी निम्नलिखित है
> db.getDistinctWithSortedDataDemo.distinct("StudentAge").sort(); यह निम्नलिखित आउटपुट उत्पन्न करेगा
[ 20, 21, 22, 23 ]