Inserting Documents in MongoDB
Introduction
Hello there! This lesson covers an essential aspect of working with MongoDB: inserting documents into MongoDB collections. The ability to add data to your database is fundamental for any application. Let’s dive into MongoDB’s data insertion mechanisms and explore the structure of the documents you will be inserting.
Two Ways to Insert Data
MongoDB offers two primary methods to insert data into collections:
-
insertOne(): Inserts a single document into a collection.
-
insertMany(): Inserts multiple documents into a collection.
Inserting a Single Document
Using the insertOne() method, you can add a single document to a collection. Here is an example where we insert a single book into the books collection:
In this example, the command db.books.insertOne() inserts the specified document into the books collection.
Inserting Multiple Documents
To add multiple documents at once, you can use the insertMany() method, which requires an array of documents as its parameter. Below is an example that inserts two books into the books collection:
In this example, the insertMany() method is used to insert an array of document objects, where each object represents a book. This command adds both books to the books collection. Note that this function accepts an array of documents, denoted by the square brackets [].
