MongoDB: Create Collection

In one of our previous tutorials, we have already created a database called books.

In MongoDB, a database consists of collections and a collection consists of documents (or "records"). A particular collection can only belong to one database.

To begin creating a collection, you need to start the Mongo Daemon first.

If you are using a Mac, open your terminal and type the below command:

				
					$ mongod
				
			

Then open another new terminal ( + T) and start the Mongo Shell.

				
					$ mongo
				
			
mongod and mongo shell

If you are using Windows, go to the /bin directory and double-click on the Mongo Daemon mongod.exe. And in the same /bin directory, double-click on mongo.exe next. This is the Mongo Shell from where you will be entering commands.

Now, as mentioned earlier, we already have created a database called books.

In MongodDB, collections are analogous to tables in relational databases. This is where documents (or records) are stored.

To create a collection called comics inside the books database, we first switch to the books database and next make use the createCollection() method as follows:

				
					$ use books
					$ db.createCollection('comics')
				
			
mongodb create collection

You will be learning how to view all collections in a database in the next tutorial.