7.
Implement the following functions using MongoDB:
a. Count
b. Sort
c. Limit
d. Skip
e. Aggregate
AIM
To implement MongoDB functions such as Count, Sort, Limit, Skip, and Aggregate on a
collection.
OBJECTIVE
To understand basic CRUD operations in MongoDB
To perform data retrieval and manipulation
To learn aggregation framework for data analysis
THEORY
MongoDB is a NoSQL database that stores data in JSON-like documents.
Key Functions:
Count → Counts number of documents
Sort → Arranges documents in order
Limit → Restricts number of records
Skip → Skips records (used in pagination)
Aggregate → Performs advanced data processing (like SQL GROUP BY)
REQUIREMENTS
Software:
MongoDB Server
MongoDB Shell (mongosh)
System:
Linux / Windows / Mac
Minimum 4GB RAM
1
ANALYSIS
MongoDB provides efficient querying using functions like countDocuments() and sort()
limit() and skip() help in pagination (used in websites like Amazon, Instagram)
Aggregation framework allows complex data analysis similar to SQL operations
The database handles structured and semi-structured data efficiently
RESULT
The MongoDB functions Count, Sort, Limit, Skip, and Aggregate were successfully
implemented and executed. The outputs were verified and found correct.
Code & Expected Output
Step 1: Start MongoDB Server
/usr/local/mongodb/bin/mongod --dbpath /data/db
Step 2: Open Mongo Shell
mongosh
Step 3: Check Current Database
db
Output:
test
Step 4: Create / Switch Database
use mydatabase
Step 5: Insert Data
[Link]([
{ name: "Alice", age: 25, city: "Bangalore" },
{ name: "Bob", age: 30, city: "Mumbai" },
{ name: "Charlie", age: 35, city: "Delhi" },
{ name: "David", age: 28, city: "Bangalore" },
{ name: "Eve", age: 22, city: "Mumbai" }
])
2
a) Count
[Link]()
[Link]({ city: "Mumbai" })
b) Sort
[Link]().sort({ age: 1 }) Ascending order
[Link]().sort({ age: -1 }) Descending order
c) Limit
[Link]().limit(3)
d) Skip
[Link]().skip(2)
Pagination:
[Link]().skip(2).limit(2)
e) Aggregate
Group by city
[Link]([
{ $group: { _id: "$city", total: { $sum: 1 } } }
])
Average age
[Link]([
{ $group: { _id: "$city", avgAge: { $avg: "$age" } } }
])
Match + Group
[Link]([
{ $match: { age: { $gt: 25 } } },
{ $group: { _id: "$city", count: { $sum: 1 } } }
])
3
EXPECTED OUTPUT
Count
Sort (Ascending)
Limit
4
Skip
Aggregate Output