Course Content
MONGODB Tutorial
About Lesson

Creating and inserting documents

MongoDB is a popular NoSQL database that provides a flexible and scalable solution for handling large amounts of unstructured data. In this guide, we will focus on the fundamental aspect of MongoDB – creating and inserting documents.

Document-oriented Data Model

MongoDB uses a document-oriented data model, which means data is stored in JSON-like BSON documents. Each document can have a different structure, allowing for dynamic and schema-less data representation.

Creating a Database

To get started, you need to create a MongoDB database. Use the use command followed by the desired database name. If the database doesn’t exist, MongoDB will create it for you.

use mydatabase

Inserting Documents

Now, let’s explore how to insert documents into a collection. MongoDB uses the insertOne and insertMany methods for this purpose.

Inserting a Single Document

To insert a single document, use the insertOne method. Specify the document as a JSON object.

db.myCollection.insertOne({
key1: value1,
key2: value2,
// additional fields
})

Inserting Multiple Documents

For inserting multiple documents, utilize the insertMany method. Pass an array of documents to be inserted.

db.myCollection.insertMany([
{
key1: value1,
key2: value2,
// additional fields
},
{
key1: value3,
key2: value4,
// additional fields
},
// additional documents
])

Bulk Write Operations

MongoDB also supports bulk write operations, allowing you to perform multiple write operations with a single command for better efficiency.

var bulk = db.myCollection.initializeUnorderedBulkOp();

bulk.insert({
key1: value1,
key2: value2,
// additional fields
});

bulk.insert({
key1: value3,
key2: value4,
// additional fields
});

bulk.execute();