Lecture Notes Of Day 5:
MongoDB CRUD
Operations – Part 1 (Insert)
Objective:
Learn how to insert
documents into MongoDB collections.
Outcome:
Students will be able to
insert a single document and multiple documents into MongoDB.
1. Introduction to CRUD
Operations in MongoDB
CRUD stands for Create,
Read, Update, and Delete, which are the four basic operations for managing
data in a database. In MongoDB, these operations are used to interact with
collections in a database. Today, we will focus on the Create operation,
which is used to insert documents into a collection.
2. MongoDB Collections
and Documents
Before diving into the
insert operations, it's important to understand the core structure of MongoDB:
- Database:
A database is a container for collections. MongoDB can have multiple
databases.
- Collection:
A collection is a group of MongoDB documents. It is similar to a table in
relational databases.
- Document:
A document is a record in MongoDB. Each document is stored in BSON format
(Binary JSON). Documents are similar to rows in relational databases.
3. Inserting Documents in
MongoDB
MongoDB provides several
methods to insert documents into collections. These methods are part of the MongoDB
Driver and can be used directly from the MongoDB Shell or in various
programming languages using appropriate MongoDB drivers (Node.js, Python, Java,
etc.).
3.1 Inserting a Single
Document
To insert a single
document, we use the insertOne() method. This method inserts one document into
a collection.
Syntax:
db.collection.insertOne(document)
- db:
Refers to the current database.
- collection:
Refers to the collection in the database.
- document:
A valid BSON document to be inserted into the collection.
Example:
use myDatabase; // Switch to the database
name: "John Doe",
age: 30,
email: "john.doe@example.com",
isActive: true
});
In this example:
- We
switch to the myDatabase database.
- We
use insertOne() to insert a document with fields name, age, email, and isActive
into the users collection.
Result:
The document is
successfully inserted into the collection. MongoDB will automatically assign an
_id field to the document if it is not provided.
3.2 Inserting Multiple
Documents
To insert multiple
documents, we use the insertMany() method. This method allows you to insert an
array of documents into a collection.
Syntax:
db.collection.insertMany([document1, document2, ...])
- document1,
document2, ...: An array of valid BSON documents to be inserted into the
collection.
Example:
db.users.insertMany([
{ name: "Alice", age: 28, email: "alice@example.com",
isActive: true },
{ name: "Bob", age: 25, email: "bob@example.com",
isActive: false },
{ name: "Charlie", age: 35, email: "charlie@example.com",
isActive: true }
]);
In this example:
- We
use insertMany() to insert three documents into the users collection.
Result:
All three documents will
be inserted into the collection. MongoDB will automatically assign a unique _id
field to each document.
4. Handling Errors during
Insertion
When inserting documents,
it's possible to encounter errors. Some common errors include:
1.
Duplicate _id:
If you try to insert a document with an _id that already exists in the
collection, MongoDB will return an error. You can manually provide an _id field
if needed, but it must be unique across the collection.
db.users.insertOne({
_id: 1,
name: "Eve",
age: 22,
email: "eve@example.com"
});
If the _id already
exists, MongoDB will return a duplicate key error.
2.
Invalid Document Format:
MongoDB documents must be in BSON format, and certain fields (like _id) must be
valid. For example, trying to insert a document with an empty object or an
array of invalid values may result in an error.
5. Checking Inserted
Documents
After inserting
documents, you can verify their insertion using the find() method to query the
documents from the collection.
Example:
db.users.find().pretty(); // Display all documents in the 'users' collection
This will display all the
documents stored in the users collection in a human-readable format.
6. MongoDB Insert with
Node.js Example
Here is an example of
using MongoDB's Node.js driver to insert documents into a collection.
Installation:
npm install mongodb
Code Example:
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // MongoDB server URL
const client = new MongoClient(uri);
await client.connect();
const database = client.db("myDatabase");
const usersCollection = database.collection("users");
name: "David",
age: 40,
email: "david@example.com",
isActive: true
};
const result = await usersCollection.insertOne(user);
console.log(`User inserted with _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
In this Node.js example:
- We
connect to the MongoDB server running on localhost:27017.
- We
select the myDatabase database and the users collection.
- We
use insertOne() to insert a document into the users collection.
- After
the insertion, we print the _id of the newly inserted document.
7. Summary
In this session, we
learned how to:
- Use
insertOne() to insert a single document into a collection.
- Use
insertMany() to insert multiple documents into a collection.
- Handle
potential errors like duplicate _id values and invalid document formats.
- Query
inserted documents to verify their presence in the collection.
In the next session, we
will focus on Reading documents from MongoDB, which will allow us to
retrieve and display data from the collections.
Assignments
1.
Insert a Single Document:
o Insert
a document into the products collection with fields like name, price, and category.
2.
Insert Multiple Documents:
o Insert
multiple products into the products collection with different name, price, and category.
3.
Insert Document with Custom _id:
o Insert
a document into the employees collection with a custom _id and verify its
insertion.
4.
Insert Invalid Document:
o Try
inserting a document with a duplicate _id and observe the error.
