Monday, 29 May 2017

MONGODB Insertion ~ GNIITHELP

Data insertion in MongoDB

We will continue with our Collection User for data insertion. Let us consider various scenarios for inserting data in Collection User.
  1. Suppose, we want to create a document in Collection User with fields name and description, we will make use of following code snippet
    Data Insertion in MongoDB
    In, the above code snippet, we used getCollection() method in order to get the existing Collection User. An object of BasicDBObject is created and fields (“name” and “description”) are appended with values. Output generated can be found by using MongoDB Compass.

    Data Insertion in MongoDB
    The output for our Query is
    XYZ against field name.
    Data insertion in MongoDB against filed description.
    
  2. While creating document in Collection MongoDB provides its own unique id referred by field_id. If we want to provide our own custom id, we can provide it. Refer the below code snippet for the same.
    Data Insertion in MongoDB

    The above query output is :
    Data Insertion in MongoDB
    In the output, we can find that document is created with our unique custom id: _id:”xyz123”.

No comments:

Post a Comment