Inserting Data (a.k.a Document) into MongoDB

After a long break time, I will continue my post about mongoDB. Now I will share about inserting data into MongoDB. In this post, I will use mongoDB console to insert data. Ok, I will start the explanations with mongoDB console. 

  1. Don’t forget to turn on mongoDB services (you can see the previous post about it). Before we can insert data into mongoDB’s collection, we must create database first. In this case, I will create Music CD Collection.
    use MusicCDCollection
  2. After create a database, you can insert your data into collection without need to declare any structure and data type for each structure. For example, I will insert this code below.
    db.music.insert({singer:"Afgan",albumtitle:"Confession No. 1",Label:"Wanna B Production"})

    This code will generate a collection named music automatically and insert data into it consider to data that we input in that statement. If your statement is right, mongoDB will inform you “WriteResult({ “nInserted” : 1 })”. To show the data, just type:

    db.music.find()

    You will see the result below.

    The Result of db.music,find()

    The Result of db.music,find()

    or you can modify the statement to show the data in json form:

    db.music.find().forEach(printjson)

    You can see the result below.

    View Data in JSON Form

    View Data in JSON Form

  3. You can also insert your data wit another way. If you want to use this second way, you must declare a variable to save your data temporarily before insert it into collection. This picture will give you example.
    Declare a Variable to Insert Data into Collection

    Declare a Variable to Insert Data into Collection

    In the next post, I will share about insert embedded document in MongoDB. See you…

Leave a comment