Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để giới hạn số lượng bản ghi, trong khi truy xuất dữ liệu từ bộ sưu tập MongoDB bằng Java?

Trong khi truy xuất bản ghi từ bộ sưu tập MongoDB, bạn có thể giới hạn số lượng bản ghi trong kết quả bằng cách sử dụng

giới hạn () phương pháp.

Cú pháp

db.COLLECTION_NAME.find().limit(no.of records needed)

Thư viện Java MongoDB cung cấp một phương thức có cùng tên, để giới hạn số lượng bản ghi gọi phương thức này (trên kết quả của phương thức find ()) bỏ qua một giá trị số nguyên đại diện cho số lượng bản ghi được yêu cầu.

Ví dụ

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
public class LimitingRecords {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Connecting to the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection object
      MongoCollection<Document>collection = database.getCollection("students");
      Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
      Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam");
      Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi");
      Document document4 = new Document("name", "Radha").append("age", 28).append("city", "Mumbai");
      Document document5 = new Document("name", "Ramani").append("age", 45).append("city", "Pune");
      //Inserting the created documents
      List<Document> list = new ArrayList<Document>();
      list.add(document1);
      list.add(document2);
      list.add(document3);
      list.add(document4);
      list.add(document5);
      collection.insertMany(list);
      System.out.println("Documents Inserted");
      //Retrieving a collection object
      collection = database.getCollection("students");  
      //Retrieving the documents with a limit
      FindIterable<Document> iterDoc = collection.find().limit(3);
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }

   }
}

Đầu ra

Documents Inserted
Document{{_id=5e887b16dac53c7f07cfd740, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e887b16dac53c7f07cfd741, name=Robert, age=27, city=Vishakhapatnam}}
Document{{_id=5e887b16dac53c7f07cfd742, name=Rhim, age=30, city=Delhi}}