- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
MongoDB - Java
- MongoDB - Java Setup
- MongoDB - Java - Create Collection
- MongoDB - Java - Get Collection
- MongoDB - Java - Insert Document
- MongoDB - Java - Retrieve Documents
- MongoDB - Java - Update Document
- MongoDB - Java - Delete Document
- MongoDB - Java - Drop Collection
- MongoDB - Java - List Collections
MongoDB - PHP
- MongoDB - PHP Setup
- MongoDB - PHP - Create Collection
- MongoDB - PHP - Get Collection
- MongoDB - PHP - Insert Document
- MongoDB - PHP - Retrieve Documents
- MongoDB - PHP - Update Document
- MongoDB - PHP - Delete Document
- MongoDB - PHP - Drop Collection
- MongoDB - PHP - List Collections
MongoDB - Advanced
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
MongoDB - Useful Resources
MongoDB - Java - Create Collection
MongoDB provides MongoDatabase class to create a collection.
Syntax
// Connect to Database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create a collection
database.createCollection("sampleCollection");
Creating a Collection
To create a collection, we first need to connect to a database and then create the collection as shown below −
package com.tutorialspoint.mongodb;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
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");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}
}
Output
Now, let's compile and run the above program to create a collection in our database myDb.
On executing, the above program gives you the following output.
Connected to the database successfully Collection created successfully
Advertisements