In MongoDB, documents are used to store data inside collections.
We can insert a single document or multiple documents using
MongoDB Shell (mongosh). In this lesson, you will learn
insertOne(), insertMany(), document
structure, and how to verify inserted records.
Document insertion means adding new data to a MongoDB collection. A document contains fields and their values, similar to a record in a relational database.
Example document:
{
name: "Rahul",
age: 20,
course: "ADCA"
}
Here, name, age, and
course are fields.
MongoDB stores documents in BSON format and normally
generates a unique _id field automatically
when you do not provide one.
First, select a database named school.
use school
Create the students collection if it does
not already exist.
db.createCollection("students")
If the collection already exists, you can continue using it without creating it again. MongoDB can also create a collection automatically when you first insert data into it.
The insertOne() method inserts one document
into a collection.
db.students.insertOne({
name: "Rahul",
age: 20,
course: "ADCA",
city: "Aurangabad"
})
Example of a successful response:
{
acknowledged: true,
insertedId: ObjectId('...')
}
The generated insertedId identifies the
newly inserted document. Its exact value will differ
each time.
db.students.find()
This command displays documents stored in the
students collection.
Use insertMany() when you want to insert
several documents in one operation.
db.students.insertMany([
{
name: "Amit",
age: 21,
course: "Tally Prime",
city: "Patna"
},
{
name: "Priya",
age: 19,
course: "Web Development",
city: "Gaya"
},
{
name: "Neha",
age: 22,
course: "Python",
city: "Aurangabad"
}
])
The square brackets [] contain an array
of documents. Each document is enclosed in curly braces
{}.
db.students.find()
db.students.countDocuments({})
The count includes all documents currently in the collection, including any records inserted earlier.
MongoDB documents can contain strings, numbers, Boolean values, arrays, nested documents, and dates.
db.students.insertOne({
name: "Suman",
age: 20,
feesPaid: 5000,
active: true,
skills: ["HTML", "CSS", "JavaScript"],
address: {
city: "Patna",
state: "Bihar"
},
admissionDate: new Date()
})
In this example:
name is a string.age and feesPaid are numbers.active is a Boolean value.skills is an array.address is a nested document.admissionDate is a date value.
MongoDB normally generates an _id automatically.
You can also supply your own unique value.
db.students.insertOne({
_id: "STU101",
name: "Ravi",
age: 21,
course: "Python"
})
You can retrieve this document using its custom ID:
db.students.findOne({
_id: "STU101"
})
Important: Each document in a collection
must have a unique _id. Inserting another
document with the same ID will normally result in a
duplicate-key error.
You can store additional fields whenever required. Documents in the same collection do not all need to have exactly the same fields.
db.students.insertMany([
{
name: "Anjali",
course: "ADCA",
feesPaid: 3000
},
{
name: "Vikas",
course: "Python",
feesPaid: 5000,
scholarship: true
}
])
The second document contains an extra field named
scholarship. This flexibility is one of
MongoDB's useful features.
Find students whose scholarship value is true:
db.students.find({
scholarship: true
})
A duplicate _id can cause an insertion
to fail because each document needs a unique ID.
Check commas, quotation marks, brackets, and braces. Each field must have a valid value.
Confirm that you are inserting into the intended
collection, such as db.students.
Make sure that values use the intended type. For example,
use age: 20 for a numeric age rather than
age: "20" if you want a number.
| Feature | insertOne() | insertMany() |
|---|---|---|
| Purpose | Insert one document | Insert multiple documents |
| Input | One document object | An array of documents |
| Example | db.students.insertOne({...}) |
db.students.insertMany([{...}]) |
| Common use | Register one student | Import several student records |
Run the following commands in order to practise inserting and verifying documents.
use school
db.students.insertOne({
name: "Karan",
age: 20,
course: "JavaScript"
})
db.students.insertMany([
{
name: "Pooja",
age: 19,
course: "HTML"
},
{
name: "Manish",
age: 22,
course: "Python"
}
])
db.students.find().pretty()
db.students.find({
course: "Python"
})
db.students.countDocuments({})
These commands demonstrate how to insert, retrieve, filter, and count student documents.
Create a database named college and practise
inserting documents into a collection named
students.
insertOne().insertMany()._id.1. Which method inserts one document?
2. Which method inserts multiple documents?
3. What happens if you do not provide _id?