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:
title: "My first blog",
body: "this is a long post..."
And another one is like:
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.
Optional: Creating/Changing a Database from Mongo Shell Script
You can change/create a new database using script as follows.
db = db.getSisterDB('databaseName');
db = db.getSiblingDB('databaseName');
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.
Creating a Collection
In MongoDB, you don't have to create a collection seperately either. Just inserting a document will create a new collection.
In my next article, I will cover everything about inserting documents in the collection.
Optional: Creating a Collection from Mongo Shell Script
Now run the script with the following command from the terminal.
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.
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.