Create Databases and Collections in MongoDB

Shahriar Shovon

Supported OS

  • All

Categories

Share this post with your friends

In this post, I will talk about MongoDB database and collection.

What is a Collection?

In my earlier post, I talked about MongoDB document. A collection is simply a group of similar documents.

MongoDB: A Schema-less Database

Strictly speaking the documents need not be similar, because MongoDB don't enforce any Schema on collection. Of course, you can use a library like Mongoose to enforce Schema but MongoDB on the server do not have any idea of it. So MongoDB accepts differences in the documents in the same collection. For example, let's say one of the document is: { _id: 1, title: "My first blog", body: "this is a long post..." } And another one is like: { _id: 2, title: 'My second blog', body: 'this is another post...', author: "Shahriar Shovon" } If I compare these two documents, you can see that the first one dont have a author key and the second one do have one. But because of the Schema less design of MongoDB, we can insert both of these documents in the same collection.

Creating a Database

In MongoDB, you don't have to create a database seperately. You just use it. use databaseName

Optional: Creating/Changing a Database from Mongo Shell Script

This section is for people who want to write scripts for Mongo Shell with JavaScript. You can change/create a new database using script as follows. Filename: create_db.js db = db.getSisterDB('databaseName'); // or db = db.getSiblingDB('databaseName'); // or db = db.getMongo().getDB('test'); Then to run it, just go to the directory where the file create_db.js is created and use the following command from the command line. mongo create_db.js

Creating a Collection

In MongoDB, you don't have to create a collection seperately either. Just inserting a document will create a new collection. db.collectionName.insert(JSONDocument) In my next article, I will cover everything about inserting documents in the collection.

Optional: Creating a Collection from Mongo Shell Script

Filename: create_collection.js db.createCollection('collectionName'); Now run the script with the following command from the terminal. mongo create_collection.js This should create an empty collections

What databases do I have on MongoDB right now?

You can check what databases are currently available using the following command from mongo shell. show dbs

What collections do I have on MongoDB right now?

To check what collections are available for you right now, run the following command from mongo shell. show collections