MongoDb Basics

Introduction of MongoDB

MongoDB is open source document oriented and NoSQL database. MongoDB is written in C++ language.

Database : A Database is a bucket which stores collections.

Collection : A collection is a group of documents (similar to a table in SQL). Collections do not enforce a schema.

Document : A document is a set of key-value pairs. The documents in the same collection do not need to have a same fields or structure in MongoDB. Documents in the same collection can hold different types of data.

Some useful commands

1. Find out the current database you are in:

db

2. Listing out the databases:

show databases

3. Go to a particular database :

use <database_name>
eg : use logisticsDB

4. Creating a Database:

use <new_database_name>

If the database with new_database_name is already present then it will navigate into existing database and if new_database_name does not exist it will create a new database.

5. Creating a Collection:

db.createCollection("testCollection")

6. Inserting data into a Collection:

  1. insertOne() is used to insert one document into a collection.

  2. insertMany() is used to insert more than one document into a collection.

  3. insert() is used to insert as many document into a collection.

Some examples below :-

  • insertOne()

    db.testCollection.insertOne({"name": "Tom", "age" : 20, "email": "tom@gmail.com"})
    
  • insertMany()

    db.testCollection.insertMany(
    {"name": "Tom", "age" : 20, "email": "tom@gmail.com"},
    {"name": "David", "age" : 21, "email": "david@gmail.com","city":"London"}
    )
    

    Note we have added a new field city for 2nd document. Also, insert() method is similar as insertMany()

7. Reading data from Collection:

To fetch all the documents

db.testCollection.find()  // gives all the documents for testCollection

To fetch documents based on some condition

db.testCollection.find({name:"Tom"})  // gives all the documents for testCollection with name = Tom

8. Updating documents in a Collection:

To update the age field whose current value is 22 update($set) it to 24.

db.testCollection.update({age : 22}, {$set: {age: 24}})

Thanks for reading!