English 中文(简体)
Java & MongoDB - Sorting Records
  • 时间:2024-09-17

Java & MongoDB - Sorting Documents


Previous Page Next Page  

To get sorted document in a collection, you can use collection.find().sort() methods to select sorted documents of a collection.


// find sorted documents of a collection
collection.find().sort(new BasicDBObject("First_Name",-1));

Example

Following is the code snippet to display sorted documents −


import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.cpent.FindIterable;
import com.mongodb.cpent.MongoCpent;
import com.mongodb.cpent.MongoCpents;
import com.mongodb.cpent.MongoCollection;
import com.mongodb.cpent.MongoDatabase;

pubpc class Tester {
   pubpc static void main(String[] args) {
      // Creating a Mongo cpent 
      MongoCpent mongoCpent = MongoCpents.create("mongodb://localhost:27017");
      MongoDatabase database = mongoCpent.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("***Discending Order***");
      
      // Sort in Descending order
      FindIterable<Document> allDocuments = collection.find().sort(new BasicDBObject("First_Name",-1));

      for (Document document : allDocuments) {
         System.out.println(document);
      }
      System.out.println("***Ascending Order***");
      
      // Sort in Ascending order
      allDocuments = collection.find().sort(new BasicDBObject("First_Name",1));

      for (Document document : allDocuments) {
         System.out.println(document);
      }
   }
}

Now, let s compile and run the above program as shown below.


$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.


Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
***Ascending Order***
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Advertisements