MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Java - Getting/Setting a Collection



MongoDB provides MongoDatabase class to get or select a collection.

Syntax

// Connect to Database
MongoDatabase database = mongoClient.getDatabase("myDb");

// Select a collection 
MongoCollection<Document> collection =  database.getCollection("sampleCollection"); 

Selecting a Collection

To select a collection, we first need to connect to a database and then select the collection as shown below −

package com.tutorialspoint.mongodb;

import org.bson.Document;

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

public class MongoDBTester { 
   
   public static void main( String args[] ) { 

      String uri = "mongodb://localhost:27017/";

      try (MongoClient mongoClient = MongoClients.create(uri)) {
         MongoDatabase database = mongoClient.getDatabase("myDb");

         System.out.println("Connected to the database successfully");
         // Selecting a collection 
         MongoCollection<Document> collection =  database.getCollection("sampleCollection"); 
         System.out.println("Collection selected successfully"); 
      }
   } 
}

Output

Now, let's compile and run the above program to select a collection from our database myDb.

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

Connected to the database successfully
Collection created successfully
Advertisements