- Java & MongoDB Tutorial
- Java & MongoDB - Home
- Java & MongoDB - Overview
- Java & MongoDB - Environment Setup
- Java & MongoDB Examples
- Java & MongoDB - Connect Database
- Java & MongoDB - Show Databases
- Java & MongoDB - Drop Database
- Java & MongoDB - Create Collection
- Java & MongoDB - Drop Collection
- Java & MongoDB - Display Collections
- Java & MongoDB - Insert Document
- Java & MongoDB - Select Document
- Java & MongoDB - Update Document
- Java & MongoDB - Delete Document
- Java & MongoDB - Embedded Documents
- Java & MongoDB - Referenced Documents
- Java & MongoDB - Limiting Records
- Java & MongoDB - Sorting Records
- Java & MongoDB Useful Resources
- Java & MongoDB - Quick Guide
- Java & MongoDB - Useful Resources
- Java & MongoDB - Discussion
Java & MongoDB - Limiting Documents
To select a given number of document in a collection, you can use collection.find().limit() methods to select required no. of documents of a collection.
int n = 2; // find required documents of a collection collection.find().limit(n);
Example
Following is the code snippet to display limited documents −
import org.bson.Document; 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://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("myDb"); // Get the collection MongoCollection<Document> collection = database.getCollection("sampleCollection"); // Find two documents FindIterable<Document> allDocuments = collection.find().limit(2); 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}}
Advertisements