Insert documents in MongoDB

Insert documents in MongoDB

In this Blog, we will learn about Insert documents in MongoDB Collection.

To Insert document there are 3 ways.

  • insert()
  • insertOne()
  • insertMany()

We will understand the use of each one.

insert()

It is deprecated already.

insertOne()

If you want to insert only single document thn you can use this method.

Syntax

db.COLLECTION_NAME.insertOne(document)

Example

So you can insert one document as below

insertMany()

If you are inserting multiple documents then instead of adding one by one using insertOne() you

can you insertMany() to save multiple documents and avoid multiple queries to mongodb.

You have pass array of documents into this method, Once you use this function it returns the acknowledge status and object of inserted ids which you can utilize for other operations.

If your documents has are not valid mongodb will stop the insert

You can use below example

Hope you like this blog so share with your friends and visit us again.

Leave a Reply
Your email address will not be published. *