MongoDB insertOne() Method: Inserting a Single Document into a Collection

In MongoDB, data is stored as documents in a collection, these documents can be retrieved, updated, deleted or inserted using various built-in methods.

To insert a new document into a MongoDB collection, there are two methods that are mainly used, insertOne() and insertMany().

In this tutorial, we will delve deeper into inserting a document into the MongoDB collection using MongoShell and NodeJS by implementing the insertOne() method.

MongoDB insertOne() Method

The insertOne() is the most basic function that we come across when using MongoDB. It allows us to insert a single document at a time. Moreover, you can even create a collection and add a single document using the insertOne() method parallelly.

We even do not need to specify an ’_id’ property for the document we add, as the insertOne() method adds it automatically.

Syntax:

Following is the syntax of insertOne() method.

db.collection.insertOne(
doc,
{
    writeConcern: doc
})

Parameters:

  • collection is the name of the collection in which you want the documents to be inserted,
  • doc is the JSON document containing keys and values that will be inserted,
  • writeConcern is an optional parameter, it is used when you do not want to use the default write concern, and it allows you to control the acknowledgement behaviour for write operations (majority of the time it is not required to pass this)

Return:

The InsertOne() method returns an object that has the following properties:

  • acknowledged: A Boolean value indicating whether write concerns is enabled or disabled,
  • insertedId: This represents the _id value of the inserted document representing the unique identifier assigned to the newly inserted document.

Note: In MongoDB, each document or record has a unique identifier called the “_id” field, while inserting a new document make sure this key must be unique otherwise you will get a duplicate key error. To avoid this, do not explicitly provide a value for the “_id” field so that MongoDB will generate it automatically.

Examples of MongoDB insertOne() Method

Let’s see how we can implement the above syntax to insert a document using both Mongo Shell and Node.

Using insertOne() Method in Mongo Shell

To use the insertOne() method in Mongo Shell, follow the steps given below:

  • Start up your MongoDB service.
  • Pick the database you want to use and navigate into it.
show dbs
use droneSpree
  • Take a look at all our existing documents in the chosen collection.
> db.drones.find({}).pretty()

{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1e"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Shadow X-copter C32",
        "price" : 69500,
        "weight" : "65 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Delivery",
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1f"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Tranzm8 Dree RFD",
        "price" : 78500,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe20"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Sierra Gane’s Qatacopter J90",
        "price" : 89500,
        "weight" : "10 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}

Here we have used the find() method to fetch all documents and then used the pretty() method, if you want to know what it is, check out the tutorial: Pretty Print in MongoDB: What it is & How to Use it? [Ultimate Guide]

  • Now, let’s insert a new document into this collection using the insertOne() function.
> db.drones.insertOne({
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Jennifer Steele’s Pegacopter PU-6",
        "price" : 29500,
        "weight" : "14 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Videography",
                        "Recreation"
                ]
        }
})

This is what the insertOne() function returns:

{
        "acknowledged" : true,
        "insertedId" : ObjectId("6161dcb013ca7f1ba14cfe21")
}
  • Let us look at what our collection now looks like now.
> db.drones.find({}).pretty()

{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1e"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Shadow X-copter C32",
        "price" : 69500,
        "weight" : "65 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Delivery",
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1f"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Tranzm8 Dree RFD",
        "price" : 78500,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe20"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Sierra Gane’s Qatacopter J90",
        "price" : 89500,
        "weight" : "10 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161dcb013ca7f1ba14cfe21"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Jennifer Steele’s Pegacopter PU-6",
        "price" : 29500,
        "weight" : "14 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Videography",
                        "Recreation"
                ]
        }
}

You can see here that the insertOne() function has successfully inserted the specified 1 document into the given collection. Also, you have noticed that the insertOne() function has automatically generated the ‘_id’.

Using insertOne() Method in Node.js

The syntax for using the insertOne() method to insert a single document into a collection in Node.js is quite different from that in Mongo Shell.

Syntax: 

database.collection(collection name).insertOne(doc, function(err, res) {
    // callback body
});

Parameters:

  • database is a database object,
  • collectionName is the name of a collection,
  • doc includes a record to be inserted

Example:

Below is an example to insert a single record in a collection using insertOne() method in Node.js.

const { MongoClient } = require('mongodb');
 
MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db("newdatabase");
 
  const doc = { name: "userName", email: "[email protected]" };
 
  database.collection("users").insertOne(doc, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
  });
});

Run the Code:

  • To run the above code, create a project folder, and copy and paste it into a JavaScrip file “app.js”.
  • Then locate the folder in the terminal and execute the below command to install the MongoDB module.
npm i mongodb
  • Then execute the below command to run the code of the “app.js” file.
node app.js

Also learn: Node.js vs Vanilla JavaScript

Conclusion

In this article, we discussed inserting a new document in the MongoDB collection using Mongo Shell and Node.js. Both ways use the same method insertOne() but the approach and parameters are slightly different. In Node.js it takes an optional callback function which provides more control over the error handling and handling the result after the operation. We hope you enjoyed reading the tutorial.

Reference

Insert Documents  — MongoDB Manual

Aneesha S
Aneesha S
Articles: 171