MongoDB: Inserting Documents
Subject: nodejs
MongoDB: Inserting Documents
Inserting documents in MongoDB is the process of adding new data records into a collection. These documents are stored in a flexible, JSON-like (BSON) format, allowing for diverse data structures within the same collection.
Why Insert Documents?
Inserting documents is fundamental for populating your database with information. Whether it's adding user profiles, product details, sensor readings, or log entries, insertion operations are how new data makes its way into your MongoDB collections.
Core Concepts
- Document: The basic unit of data in MongoDB, a set of key-value pairs (like a JSON object).
- Collection: A grouping of related documents, residing within a database. Documents are inserted into collections.
Methods for Insertion
MongoDB provides two primary methods for inserting documents:
insertOne()
: Used to insert a single document into a collection.insertMany()
: Used to insert multiple documents (as an array) into a collection in a single operation, which is generally more efficient for bulk inserts.
Node.js Examples: Inserting Documents
To perform insert operations from a Node.js application, use the official MongoDB Node.js driver.
Prerequisites:
- A running MongoDB instance (local or Atlas)
- Node.js installed
- MongoDB Node.js driver:
1. Inserting a Single Document (insertOne
)
Explanation:
- Connects to
mydatabase
. - Defines
myDocument
as a JS object (converted to BSON). - Uses
insertOne()
to insert into theproducts
collection (created if not existing). res.insertedId
shows the auto-generated_id
.
Expected Output:
2. Inserting Multiple Documents (insertMany
)
Explanation:
manyDocuments
is an array of JS objects.insertMany()
inserts all at once into theproducts
collection.res.insertedCount
shows how many documents were inserted.res.insertedIds
gives the_id
for each.
Expected Output:
Key Takeaways
- Inserting is how new data is added to MongoDB.
- Use
insertOne()
for single documents,insertMany()
for bulk inserts. - Collections are implicitly created on first insert.
- MongoDB automatically assigns a unique
_id
to each document if not provided.