Mongodb Basics Set 1: Insert Operation

Mongodb Basics Set 1: Insert Operation

 


In this series, I would be sharing a few basic MongoDB articles on different operations.

1)Insert a single record in MongoDB collection.

var param={

firstname:"joey",

middlename:"",

lastname:"tribani",

phone:9898989898

}

db.collection('exampleset').insertOne(param)



This returns something like this:

{

   "acknowledged" : true,

   "insertedId" : ObjectId("56fc40f9d735c28df206d078")

}



You can also use 'insert' commond for inserting single record.

db.collection('exampleset').insert(param);

This returns :

WriteResult({ "nInserted" : 1 });





2)Insert multiple records in MongoDB collection.



var records=[{

firstname:"joey",

middlename:"",

lastname:"tribani",

phone:9898989898

},{firstname:"koey",

middlename:"",

lastname:"desuoiza",

phone:9898989898

}]



db.collection('exampleset').insertMany(records);

This returns :

{

   "acknowledged" : true,

   "insertedIds" : [

      ObjectId("562a94d381cb9f1cd6eb0e1a"),

      ObjectId("562a94d381cb9f1cd6eb0e1b"),

    

   ]

}



OR



db.collection('exampleset').insert(records)

This returns:

BulkWriteResult({

        "writeErrors" : [ ],

        "writeConcernErrors" : [ ],

        "nInserted" : 2,

        "nUpserted" : 0,

        "nMatched" : 0,

        "nModified" : 0,

        "nRemoved" : 0,

        "upserted" : [ ]

})

Notes: 

1)By default it will insert all documents in order(This is applicable to both insertMany and insert command).

If you want to change behaviour please use this commond,

db.collection('exampleset').insertMany(records,{ ordered: false });

OR

db.collection('exampleset').insert(records,{ ordered: false });

If ordered is set to true and any document reports an error then the 

remaining documents are not inserted.

If ordered is set to false then remaining documents are inserted even if an error occurs.


2)All three of these(insert,insertMany,insertOne) also allow you to define a custom writeConcern and

 also, create a collection if it doesn't exist.


3)The maximum BSON(Mongodb stores each record in BSON format) document size is 16 megabytes and

maximum bulk size write is 100,000(i.e insertMany or insert allows a maximum of 1lac documents in array). 


You Might Like:

Node.js interview questions set 1

Node JS: Understanding bin in package.json.

Node.js: Bundling your Node.js application to a single executable for Windows.

Node.js: Extract text from image using Tesseract.




Comments

Popular Posts