mongodb insert query

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We have learned how to create database and collection in mongodb. It is time we go deeper into the CRUD operations. MongoDB insert query can insert single or multiple records. This article will explain how to use mongodb insert query to insert single record.

MongoDB Insert Query:

Let us try to insert a document using mongodb insert query. The syntax for it is as below as per official reference documentation.

Forget about writeConcern and ordered as of now, you can refer in the official documents itself. We will simply write mongodb insert query to insert a document.

Some points to notice about the query.

  • db is a variable that refers to current database selected. In our case it is employee_db
  • employees is the name of collection in which we want to insert documents.
  • insert() method takes the document body as parameter.

Now after you execute mongodb insert query by hitting enter, you will see something like below.

mongodb insert query returns and object of type WriteResult where nInserted : 1 denotes that 1 record was inserted succesfully.

Check the database by retrieving all documents.

Note that mongodb insert query has automatically inserted _id field. It is auto-generated. In the next article we will learn more about _id

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

2 thoughts on “mongodb insert query

Leave a Reply

Your email address will not be published. Required fields are marked *