MongoDb Tutorial

Day 5 : Create document in MongoDB








Mongodb tutorial series

Overview

In this part of the Learn Mongo Series, we will learn how to create a document in mongodb.

Let's start

MongoDB is an Document oriented database where data is stored in the form of documents. So we can insert the data into a document using the db.Collection_name.insert() Method as shown below :

  1. Single Insert : Inserting Single document using insert() command is shown below :
    											
    >use demo_db
    switched to db demo_db
    >db.demoCollection.insert([
     > db.details.insert([
    ... {
    ... name : 'nodejsera',
    ... age : '10',
    ... description : 'Mongodb tutorial series'
    ... }])
    >
    
    											
    										

  2. Multiple Insert : Inserting multiple documents using insert() command is shown below :
    											
    >use demo_db
    switched to db demo_db
    > db.details.insert([
    ... {
    ... name : 'nodejsera',
    ... age : '10',
    ... description : 'Mongodb tutorial series'
    ... },
    ... {
    ... name : 'a',
    ... age : '11',
    ... description : 'learn mongodb'
    ... },
    ... {
    ... name : 'b',
    ... age : '12',
    ... description : 'something '
    ... }])
    >
    
    											
    										

MondoDb will automatically assign each document an unique _id . It is a 12 bytes hexadecimal number unique for every document in a collection. It is generated via keeping the following format in :
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

Hurray !! Mission Accomplished. We have successfully Created the document and inserted data into it.

Summary

In this part of learn mongo series , we learned about how we can remove documents from mongodb collection. We learned the following commands of mongodb :

  1. use : This command is use to either create a new database or switch to an already existing database.
  2. db.Collection_name.insert() : This command is used to insert documents in the mongodb collection.