Getting started with MongoDB.

Getting started with MongoDB.

Table of contents

Introduction

MongoDB is the most popular NoSQL database management system which is a document-oriented Database. Unlike the traditional relational databases which contain tables with rows and columns, MongoDB consists of collections with documents and fields.

It stores data in BSON format i.e. Binary JSON whose structure resembles to that of the JSON objects representation.

  1. To create a new database:

     use <database name>
    

    The following command accomplishes two things-

    • Initially, it verifies the existence of a database with the specified name to utilize it.

    • If the database does not exist it creates a new database of the given name.

  2. To check existing databases:

     show dbs
    

    Executing the following command will display a list of existing databases, including some default ones. However, databases with no data will not be shown.

    • Thus, we have the capability to create collections and add documents to them.

    • In this context, Collections function similarly to tables in MySQL, and documents are analogous to rows within those tables.

  3. Create collections and insert data:

     db.createCollection("<CollectionName>")
    

    This command will create a collection with the name provided.

     db.animalsdata.insertOne({name:"lion",type:"wild",active:true,total:50})
    

    The above query creates a collection named "animalsdata" if the collection does not exist and inserts a document with the following fields name, type, active, and total.

    • db denotes the current database

    • "insertOne" is used to insert one document into the collection.

    • After successful execution of the query it automatically creates the id if not specified which acts as the primary key.

  4. Check the existing collections in the database:

     show collections
    
    • Executing the following command will produce a list of collections present in the database.
  5. View all documents in a collection:

     falsedb> db.animalsdata.find()
    
    • This provides the series of documents in the specified collection

    • These are the two documents existing in the collection named "animalsdata".