Open In App
Related Articles

MongoDB – Insert Single Document Using MongoShell

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations and add new documents to the existing collection. You are allowed to add a single document in the collection using db.collection.insertOne() method. 

insertOne() is a mongo shell method, which can insert one document at a time. This method can be used in multi-document transactions. In this method, you can add a document to the collection with or without _id field. If you add a document without _id field, then MongoDB will automatically add a _id field and assign it with a unique ObjectId.

Syntax: 

db.collection.insertOne(
    <document>,
   {
      writeConcern: <document>
     
   }
)

Parameters: 

  • document: First parameter of this method. It represents a document that will insert in the collection.
  • writeConcern: It is an optional parameter. It is only used when you do not want to use the default write concern. The type of this parameter is document.

Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.

Examples: In the following examples, we are working with:

Database: GeeksforGeeks
Collection: student

Inserting a single document without _id field:

In this example, we are inserting a document in the student collection without _id field using db.collection.insertOne() method.

Inserting a single document with _id field:

In this example, we are inserting a document in the student collection with _id field using db.collection.insertOne() method.


Last Updated : 19 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads