 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a MongoDB collection using Java?
You can create a collection in MongoDB using the db.createCollection() method.
Syntax
db.createCollection(name, options)
Where
- db is the database. 
- name is the name of the collection you want to create. 
- Option is the set of optional parameters such as capped, auto indexed, size and, max. 
Example
> use myDatabase switched to db myDatabase > db.createCollection("myCollection") { "ok" : 1 } Using Java program
In Java, you can create a collection using the createCollection() method of the com.mongodb.client.MongoDatabase interface. This method accepts a string value representing the name of the collection.
Therefore to create a collection in MongoDB using Java program −
- Make sure you have installed MongoDB in your system 
- Add the following dependency to its pom.xml file of your Java project. 
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency>
- Create a MongoDB client by instantiating the MongoClient class. 
- Connect to a database using the getDatabase(). 
- Invoke the createCollection() method by passing the name of the collection(string). 
Example
import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; public class CreatingCollection {    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       database.createCollection("sampleCollection");       System.out.println("Collection created successfully");    } } Output
Collection created successfully
