Java 和 MongoDB - 对文档进行排序



若要获取集合中已排序的文档,可以使用 collection.find().sort() 方法来选择集合中的已排序文档。

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

示例

以下是如何显示已排序文档的代码片段:-

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://127.0.0.1:27017");
      MongoDatabase database = mongoClient.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);
      }
   }
}

现在,让我们编译和运行如下的程序。

$javac Tester.java 
$java Tester

输出

在进行执行时,上述程序会提供以下输出。

Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, [email protected], phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}}
***Ascending Order***
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, [email protected], phone=9000012345}}
广告