MongoDB – Insert Single Document Using MongoShell

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 add new documents in 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 the multi-document transactions. In this method, you can add a document in 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.deleteOne(
    <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.deleteOne() method.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.