One of the most fundamental tasks when working with any database is entering data into it. In MongoDB, data is stored as documents, which are data structures similar to JSON (JavaScript Object Notation). In this chapter, we will discuss how to insert documents into a MongoDB collection.

Before we begin, it's important to understand that in MongoDB, a database is not created until data is stored in it. Therefore, the first time we insert a document into a collection, MongoDB will create both the database and the collection for us.

Inserting a single document

To insert a single document into a collection, we use the insertOne() method. This method creates a new document if the fields in the document do not exist in the collection. If the document contains an "_id" field, the method will check the collection to see if a document with the same ID already exists. If the document exists, the method will return an error.

db.collection('collectionName').insertOne(
   { item: "item1", qty: 10 },
   function(err, result) {
     console.log(result);
   }
);

In this example, we are inserting a document with two fields, "item" and "qty", into the collection called 'collectionName'. If the insertion is successful, the method returns a result object that contains information about the operation.

Inserting multiple documents

To insert multiple documents into a collection at once, we use the insertMany() method. This method accepts an array of documents to be inserted into the collection.

db.collection('collectionName').insertMany(
   [
     { item: "item1", qty: 10 },
     { item: "item2", qty: 20 },
     { item: "item3", qty: 30 }
   ],
   function(err, result) {
     console.log(result);
   }
);

In this example, we are inserting three documents into the 'collectionName' collection. Again, if the insertion is successful, the method returns a result object that contains information about the operation.

Working with the _id field

In MongoDB, each document must have a unique "_id" field that acts as the primary key for the document. If a document being inserted does not contain an "_id" field, MongoDB will add one for us. The value of the "_id" field is an ObjectId object that is automatically generated by MongoDB.

We can also provide our own value for the "_id" field when we insert a document. However, we must ensure that the value is unique in the collection.

db.collection('collectionName').insertOne(
   { _id: "myId", item: "item1", qty: 10 },
   function(err, result) {
     console.log(result);
   }
);

In this example, we are providing our own value for the "_id" field when we insert a document. If a document with the same ID already exists in the collection, the insert operation fails.

Conclusion

Inserting documents into a collection is a basic but essential task when working with MongoDB. Through the use of the insertOne() and insertMany() methods, we can insert a single document or multiple documents into a collection at once. We also have the flexibility to provide our own value for a document's "_id" field, as long as it is unique in the collection.

Understanding how to insert documents is an important step to working effectively with MongoDB. In the next chapter, we will discuss how to query documents in a MongoDB collection.

Now answer the exercise about the content:

What is the procedure for inserting data into MongoDB?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Inserting documents into MongoDB: Introduction to MongoDB

Next page of the Free Ebook:

9Inserting documents into MongoDB: Introduction to MongoDB

3 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text