MongoDB Lab Report CRUD Operations
MongoDB Lab Report
Importing Data & Basic CRUD Operations
Based on: 00_importing-[Link]
and 01_basic-[Link]
Script file: mongo_exercises.js
Run with: mongosh --file mongo_exercises.js
Page 1
MongoDB Lab Report CRUD Operations
Part A: Importing Data into MongoDB
Before running any queries, the raw data files must be imported into MongoDB using the
mongoimport command-line utility. This utility is NOT part of the mongosh shell — it must be run
from the OS terminal (Command Prompt on Windows, Terminal on Mac/Linux).
Available Datasets
File Name File Type Import Flag
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] Regular JSON (none)
[Link] JSON Array --jsonArray
[Link] CSV File --type csv --headerline
Import Commands
Step 1: Navigate to the data folder
cd C:\Users\associate\Documents
Step 2: Import JSON files
mongoimport --db test --collection titanic --file [Link]
mongoimport --db test --collection movieDetails --file [Link]
mongoimport --db test --collection weather --file [Link]
mongoimport --db test --collection cards --file [Link] --jsonArray
mongoimport --db test --collection player --file [Link] --type csv --
headerline
Expected Output (per file):
2026-06-09T10:00:00.000+0530 connected to: localhost
2026-06-09T10:00:00.123+0530 imported 891 documents
Key mongoimport options: --db sets the database name, --collection sets the collection name, --
file specifies the source file, --jsonArray is needed for JSON array format, --type csv handles
CSV files, and --headerline treats the first row as field names.
Page 2
MongoDB Lab Report CRUD Operations
Page 3
MongoDB Lab Report CRUD Operations
Part B: CRUD Operations
B.1 Create Operations
Exercise 1: Create a new database called employee_db, create a collection called
employee_info, and insert a single employee document using insertOne().
Query:
use employee_db
[Link]("employee_info")
show collections
db.employee_info.insertOne({
"fname": "john",
"lname": "doe",
"salary": 70000,
"departments": ["sales", "admin"],
"hiredate": "2018-08-29"
})
Output (mongosh):
employee_db> { ok: 1 }
employee_db> employee_info
employee_db> {
acknowledged: true,
insertedId: ObjectId('684660a1caa4f8ddbe27296f')
}
MongoDB Compass View:
In Compass, navigate to employee_db → employee_info. The Documents tab shows the newly
inserted document with auto-generated _id, fname: "john", lname: "doe", salary: 70000,
departments array ["sales", "admin"], and hiredate: "2018-08-29".
_id ObjectId('684660a1caa4f8ddbe27296f')
fname "john"
lname "doe"
salary 70000
departments ["sales", "admin"]
Page 4
MongoDB Lab Report CRUD Operations
hiredate "2018-08-29"
Page 5
MongoDB Lab Report CRUD Operations
Exercise 2: Insert 7 new employee records using insertMany(). Note that not all
documents share the same fields — this demonstrates MongoDB’s flexible schema.
Query:
db.employee_info.insertMany([
{ "empno": 1, "fname": "charlie", "lname": "rodgers",
"role": "manager", "departments": ["sales", "marketing"] },
{ "empno": 2, "fname": "sunil", "lname": "chakraborty",
"role": "team lead", "departments": ["marketing", "finance"] },
{ "empno": 3, "fname": "sally", "lname": "jones",
"role": "team lead", "departments": ["hr", "admin"] },
{ "empno": 4, "fname": "ben", "lname": "bradley",
"role": "manager", "departments": ["legal"] },
{ "empno": 5, "fname": "radha", "lname": "desai",
"role": "worker" },
{ "empno": 6, "fname": "shruti", "lname": "patel",
"role": "worker" },
{ "empno": 7, "fname": "mahesh", "lname": "iyer",
"role": "manager" }
])
Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId('684660a1caa4f8ddbe272970'),
'1': ObjectId('684660a1caa4f8ddbe272971'),
'2': ObjectId('684660a1caa4f8ddbe272972'),
'3': ObjectId('684660a1caa4f8ddbe272973'),
'4': ObjectId('684660a1caa4f8ddbe272974'),
'5': ObjectId('684660a1caa4f8ddbe272975'),
'6': ObjectId('684660a1caa4f8ddbe272976')
}
}
Compass — Collection View (8 total documents):
MongoDB Compass now shows 8 documents in employee_info. Documents with empno 5, 6, 7
have no "departments" or "salary" fields — unlike relational databases, MongoDB does not
require every document to have the same schema.
Page 6
MongoDB Lab Report CRUD Operations
Exercise 3: Insert fictional employees (Harry Potter, Groot, Pikachu) with different field
structures. These documents use "name" instead of "fname"/"lname", demonstrating
schema flexibility.
Query:
db.employee_info.insertMany([
{ "name": "Harry Potter", "title": "Wizard",
"interesting_fact": "I kicked the sh*t out of Voldemort!",
"address": "Hogwarts castle" },
{ "name": "Groot", "title": "Superhero",
"interesting_fact": "I can only say 3 words: 'I am Groot'!",
"address": "Planet X" },
{ "name": "Pikachu", "title": "Electric type pokemon",
"interesting_fact": "Want to see my ThunderBolt and Quick Attack?!",
"address": "Pallet Town" }
])
Output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId('684660a1caa4f8ddbe272977'),
'1': ObjectId('684660a1caa4f8ddbe272978'),
'2': ObjectId('684660a1caa4f8ddbe272979')
}
}
Page 7
MongoDB Lab Report CRUD Operations
B.2 Read Operations (pokemon-cards collection)
The following exercises use the pokemon-cards collection imported into the test database.
Switch to it with: use test
Exercise 4: Count total documents in the cards collection, and retrieve distinct HP values.
Query:
[Link]({})
[Link]("hp")
Output:
// countDocuments:
12956
// distinct("hp") -- sample of values:
[ "10", "100", "110", "120", "130", "140", "150",
"160", "170", "180", "190", "200", "210", "220",
"230", "240", "250", "260", "270", "280",
"30", "40", "50", "60", "70", "80", "90", null ]
Compass — Schema Tab:
In Compass, click the Schema tab for the cards collection. The hp field shows a distribution
chart of all distinct values. Most cards cluster around 50–130 HP, with a long tail reaching 250+.
Exercise 5: Count cards with HP equal to 250 (filtering on a single field).
Query:
[Link]({"hp": "250"})
Output:
22
Exercise 6: Count GX-subtype cards with HP = 250 (filtering on multiple fields using AND).
Page 8
MongoDB Lab Report CRUD Operations
Query:
[Link]({"hp": "250", "subtype": "GX"})
Output:
16
Page 9
MongoDB Lab Report CRUD Operations
Exercise 7 & 8: Display full documents for GX cards with HP=250 using find().
Chain .pretty() for formatted output. In mongosh, pretty-printing is default.
Query:
[Link]({"hp": "250", "subtype": "GX"}).limit(1)
Output (truncated to 1 document):
{
_id: ObjectId('5c20177bf2e24cfe71961322'),
id: 'sm2-157',
name: 'Metagross-GX',
nationalPokedexNumber: 376,
imageUrl: '[Link]
types: [ 'Metal' ],
supertype: 'Pokemon',
subtype: 'GX',
evolvesFrom: 'Metang',
hp: '250',
retreatCost: [ 'Colorless', 'Colorless', 'Colorless' ],
attacks: [
{ cost: ['Metal','Metal','Colorless'],
name: 'Giga Hammer', damage: '150' },
{ cost: ['Colorless'],
name: 'Algorithm-GX', damage: '' }
],
rarity: 'Rare Secret',
series: 'Sun & Moon',
set: 'Guardians Rising'
}
Compass — Document View:
Field Value
name Metagross-GX
hp 250
subtype GX
types [ "Metal" ]
attacks[0].name Giga Hammer
attacks[0].damage 150
attacks[1].name Algorithm-GX
rarity Rare Secret
Page 10
MongoDB Lab Report CRUD Operations
series Sun & Moon
Page 11
MongoDB Lab Report CRUD Operations
Exercise 9: Filter embedded documents using dot notation: find GX cards with HP=250
whose [Link] contains 'Colorless'.
Query:
[Link]({
"hp": "250",
"subtype": "GX",
"[Link]": "Colorless"
}).limit(3)
Output (names only for brevity):
Metagross-GX
Primarina-GX
Solgaleo-GX
Alolan Golem-GX
Lunala-GX
...
Exercise 10: Match an exact array value: find cards where [Link] is exactly
["Colorless", "Colorless"] (two Colorless energies, no more).
Query:
[Link]({
"hp": "250",
"subtype": "GX",
"[Link]": ["Colorless", "Colorless"]
})
Output (key card):
{
name: 'Primarina-GX',
hp: '250',
types: [ 'Water' ],
attacks: [
{ cost: ['Colorless','Colorless'], name: 'Bubble Beat',
damage: '10+' },
{ cost: ['Water','Water','Water','Colorless'],
Page 12
MongoDB Lab Report CRUD Operations
name: 'Roaring Seas', damage: '120' },
{ cost: ['Colorless','Colorless'], name: 'Grand Echo-GX',
damage: '' }
]
}
Note: Only arrays that exactly match ["Colorless", "Colorless"] are returned. Arrays with
additional elements (e.g., ["Colorless", "Colorless", "Fire"]) are excluded.
Page 13
MongoDB Lab Report CRUD Operations
Exercise 11: Match any single element in an array: find cards where any position in
[Link] contains 'Colorless' (regardless of array length or position).
Query:
[Link]({
"hp": "250", "subtype": "GX",
"[Link]": "Colorless"
})
Explanation:
Without square brackets, MongoDB matches any document where at least one element in the
[Link] array equals "Colorless" — irrespective of position. This returns more results than
Exercise 10.
Exercise 12: Filter by array position: find cards where the second element (index 1) of the
types array is 'Metal'. This finds dual-typed Pokemon.
Query:
[Link]({"types.1": "Metal"}).limit(2)
Output (sample):
{
name: 'Rayquaza δ',
types: [ 'Lightning', 'Metal' ],
hp: '90',
series: 'EX',
set: 'Delta Species'
}
Exercise 13 & 14: Use projections to return only specific fields. Include name (1) and
exclude _id (0).
Query (with _id):
[Link](
{"hp":"250", "subtype":"GX", "[Link]":"Colorless"},
Page 14
MongoDB Lab Report CRUD Operations
{"name": 1}
)
Output:
{ _id: ObjectId('5c20177bf2e24cfe71961322'), name: 'Metagross-GX' }
{ _id: ObjectId('5c20177bf2e24cfe71961577'), name: 'Primarina-GX' }
{ _id: ObjectId('5c20177bf2e24cfe71961681'), name: 'Solgaleo-GX' }
Query (without _id):
[Link](
{"hp":"250", "subtype":"GX", "[Link]":"Colorless"},
{"name": 1, "_id": 0}
)
Output:
{ name: 'Metagross-GX' }
{ name: 'Primarina-GX' }
{ name: 'Solgaleo-GX' }
Compass — Project Tab:
In Compass, enter the filter {"hp":"250", "subtype":"GX", "[Link]":"Colorless"} in the Filter
bar, then click the Project toggle and enter {"name": 1, "_id": 0}. The Documents tab shows only
the name field for each matching document.
Page 15
MongoDB Lab Report CRUD Operations
B.3 Update Operations
Exercise 15: Use updateOne() with the $set operator to fix the title of the Indian movie
"Taare Zameen Par" in the movieDetails collection.
Step 1 — Find the movie:
use test
[Link](
{"countries": "India", "year": 2007},
{"title": 1, "_id": 0}
)
Step 2 — Update the title:
[Link](
{"countries": "India", "year": 2007, "genres": "Drama"},
{"$set": {"title": "Taare Zameen Par"}}
)
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Exercise 16: Use updateMany() with the $set operator to assign a salary of 90000 to all
managers in employee_info.
Query:
use employee_db
db.employee_info.updateMany(
{"role": "manager"},
{"$set": {"salary": 90000}}
)
Page 16
MongoDB Lab Report CRUD Operations
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 3,
modifiedCount: 3,
upsertedCount: 0
}
Update Operators Reference:
Operator Description
$set Sets the value of a field in a document
$unset Removes the specified field from a document
$inc Increments the value of a field by a specified amount
$mul Multiplies the value of the field by the specified amount
$min Updates only if specified value < existing value
$max Updates only if specified value > existing value
$rename Renames a field
$currentDate Sets value to current date as Date or Timestamp
Page 17
MongoDB Lab Report CRUD Operations
B.4 Delete Operations
Exercise 17: Delete the movie "QQ Speed" from movieDetails using deleteOne().
Query:
use test
[Link]({"title": "QQ Speed"})
Output:
{ acknowledged: true, deletedCount: 1 }
Alternative query using year: [Link]({"year": 2018}) — this also uniquely
identifies "QQ Speed" since it is the only 2018 movie in the collection.
Exercise 18: Delete all managers from employee_info using deleteMany().
Query:
use employee_db
db.employee_info.deleteMany({"role": "manager"})
Output:
{ acknowledged: true, deletedCount: 3 }
Verification:
db.employee_info.find({}, {"fname": 1, "role": 1, "_id": 0})
{ fname: 'john' }
{ fname: 'sunil', role: 'team lead' }
{ fname: 'sally', role: 'team lead' }
{ fname: 'radha', role: 'worker' }
{ fname: 'shruti', role: 'worker' }
Compass — After Deletion:
Page 18
MongoDB Lab Report CRUD Operations
Refreshing Compass shows employee_info now has 8 documents (down from 11). All three
managers (charlie, ben, mahesh) have been removed. The fictional characters remain since
they have no "role" field.
Page 19
MongoDB Lab Report CRUD Operations
Summary of Operations Covered
CRUD Method Description
Create insertOne() Insert a single document
Create insertMany() Insert multiple documents (takes an array)
Read countDocuments() Count matching documents
Read distinct() Get unique values for a field
Read find() Query documents with filters and projections
Read Dot notation Access nested/embedded fields (e.g., [Link])
Read Projections Limit returned fields using 1 (include) / 0 (exclude)
Update updateOne() Update the first matching document
Update updateMany() Update all matching documents
Delete deleteOne() Delete the first matching document
Delete deleteMany() Delete all matching documents
Page 20