Inserting Document/Record in MongoDb's Collection/Table


>_ Ways To Insert Document


  • MongoDB provides mainly 3 types of insert methods for inserting documents into a collection those are:
    sno Method Description
    1 insert() inserts a single document or multiple documents
    into a collection
    2 insertMany() Inserts multiple documents into a collection.
    3 insertOne() inserts a single document into a collection
    and returns the status of the operation

>_ insert() Syntax and Example

  • db.CollectionName.insert(
    document or array of documents of bson/json form,
    {
         writeConcern: <document>,
         ordered: <boolean>
       }
    )
    
    
    Here ordered:true preserves order of insertion default it is false. Example:-
     >db.users.insert({userid:"Alex",Age:25,gamesplayed:["Rummy","TeenPati"]})

    Output:-

     Inserted 1 record(s) in 1ms
    Here we are inserting a record/document into games collection. To view the record of above, use this command
     db.users.find().pretty()
    then we will get this output
    {
        "_id" : ObjectId("5774adbcfc520de27ab8744e"),
        "userid" : "Alex",
        "Age" : 25.0,
        "gamesplayed" : [ 
            "Rummy", 
            "TeenPati"
        ]
    }
    
    

    In the above output _id is automatically generated by MongoDB if we want to override with our custom value we can but _id is must be unique. For more details on _id check this

>_ insertMany() Syntax and Example

  • Syntax: - db.CollectionName.insertMany
    ([document1, document2,…],
    {
         writeConcern: <document>,
         ordered: <boolean>
      }
    )
    
    Here ordered:true preserves order of insertion default it is false.

    Example :-
    >db.users.insertMany([
        {userid:"Anderson",Age:40,gamesplayed:[],totalbet:0,totalwin:0},
        {userid:"McGraw",Age:45,gamesplayed:["Cricket","Rummy"],totalbet:1000,totalwin:15000,isOnline:false}
      ])
    
    Output:-
    {
        "acknowledged" : true,
        "insertedIds" : [ 
            ObjectId("5773aa2fe2b90fd312b1c480"), 
            ObjectId("5773aa2fe2b90fd312b1c481")
        ]
    }
    
    Here we are inserting multiple records at a time.

>_ insertOne() Syntax and Example

  • it will inserts one record similar to insert() method but it will acknowledge objectId of the inserted document whereas insert() won’t.

    Syntax: -

    db.CollectionName.insertOne
    (document,
    {
         writeConcern: <document>,
      ordered: <boolean>
      }
    )
    
    Here ordered:true preserves order of insertion default it is false.
    Example :-
    >db.users.insertOne({userid:"Cock",Age:45,gamesplayed:["Cricket","Teenpati"],totalbet:1000,totalwin:15000,isOnline:true})
    
    Output:-
    { "acknowledged" : true,
    "insertedId" : ObjectId("5773ab7ae2b90fd312b1c483")
    }
Copyright © 2018-2020 TutorialToUs. All rights reserved.