Nearby lessons

18 of 22

🧩 MongoDB: Array and Array Aggregation Operators

MongoDB provides a wide range of Array Operators that help you manipulate, transform, and analyze arrays inside documents. You can extract elements, merge arrays, filter items, and even perform computations using aggregation pipelines.

📚 Initial Data Setup — studentsArr Collection

MongoDB Shell
NoSQL
Database
1db.studentsArr.insertMany([
2 { _id: 1, name: "Alice", scores: [85, 92, 88, 76, 95], tags: ["js","py","mongo"] },
3 { _id: 2, name: "Bob", scores: [70, 65, 88], tags: ["java","c#"] },
4 { _id: 3, name: "Cara", scores: [100,99,98], tags: ["go","rust"] }
5]);
Query Result
JSON Output
✅ 3 student documents inserted successfully.

1️⃣ $arrayElemAt — Get Element at Index

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, secondScore: { $arrayElemAt: ["$scores", 1] } } }
3]);
Query Result
JSON Output
{ name: "Alice", secondScore: 92 }
{ name: "Bob", secondScore: 65 }
{ name: "Cara", secondScore: 99 }

2️⃣ $firstN — First N Elements

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, top2: { $firstN: { input: "$scores", n: 2 } } } }
3]);
Query Result
JSON Output
{ name: "Alice", top2: [85, 92] }
{ name: "Bob", top2: [70, 65] }
{ name: "Cara", top2: [100, 99] }

3️⃣ $lastN — Last N Elements

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, last2: { $lastN: { input: "$scores", n: 2 } } } }
3]);
Query Result
JSON Output
{ name: "Alice", last2: [76, 95] }
{ name: "Bob", last2: [65, 88] }
{ name: "Cara", last2: [99, 98] }

4️⃣ $maxN — N Largest Values

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, best3: { $maxN: { input: "$scores", n: 3 } } } }
3]);
Query Result
JSON Output
{ name: "Alice", best3: [95, 92, 88] }
{ name: "Bob", best3: [88, 70, 65] }
{ name: "Cara", best3: [100, 99, 98] }

5️⃣ $minN — N Smallest Values

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, worst2: { $minN: { input: "$scores", n: 2 } } } }
3]);
Query Result
JSON Output
{ name: "Alice", worst2: [76, 85] }
{ name: "Bob", worst2: [65, 70] }
{ name: "Cara", worst2: [98, 99] }

6️⃣ $slice — Extract Subarray

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, midScores: { $slice: ["$scores", 1, 3] } } }
3]);
Query Result
JSON Output
{ name: "Alice", midScores: [92, 88, 76] }
{ name: "Bob", midScores: [65, 88] }
{ name: "Cara", midScores: [99, 98] }

7️⃣ $sortArray — Sort Elements

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, ascScores: { $sortArray: { input: "$scores", sortBy: 1 } } } }
3]);
Query Result
JSON Output
{ name: "Alice", ascScores: [76,85,88,92,95] }
{ name: "Bob", ascScores: [65,70,88] }
{ name: "Cara", ascScores: [98,99,100] }

8️⃣ $reverseArray — Reverse Order

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, revTags: { $reverseArray: "$tags" } } }
3]);
Query Result
JSON Output
{ name: "Alice", revTags: ["mongo","py","js"] }
{ name: "Bob", revTags: ["c#","java"] }
{ name: "Cara", revTags: ["rust","go"] }

9️⃣ $size — Array Length

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, tagCount: { $size: "$tags" } } }
3]);
Query Result
JSON Output
{ name: "Alice", tagCount: 3 }
{ name: "Bob", tagCount: 2 }
{ name: "Cara", tagCount: 2 }

🔟 $in — Check Membership

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, knowsMongo: { $in: ["mongo","$tags"] } } }
3]);
Query Result
JSON Output
{ name: "Alice", knowsMongo: true }
{ name: "Bob", knowsMongo: false }
{ name: "Cara", knowsMongo: false }

1️⃣1️⃣ $indexOfArray — Find Element Index

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, posPy: { $indexOfArray: ["$tags", "py"] } } }
3]);
Query Result
JSON Output
{ name: "Alice", posPy: 1 }
{ name: "Bob", posPy: -1 }
{ name: "Cara", posPy: -1 }

1️⃣2️⃣ $isArray — Check If Field Is Array

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, isTagsArray: { $isArray: "$tags" } } }
3]);
Query Result
JSON Output
{ name: "Alice", isTagsArray: true }

1️⃣3️⃣ $map — Transform Each Element

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 upperTags: { $map: { input: "$tags", as: "t", in: { $toUpper: "$$t" } } }
5 } }
6]);
Query Result
JSON Output
{ name: "Bob", upperTags: ["JAVA","C#"] }

1️⃣4️⃣ $filter — Filter Elements

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 highScores: {
5 $filter: {
6 input: "$scores",
7 as: "s",
8 cond: { $gte: ["$$s", 90] }
9 }
10 }
11 } }
12]);
Query Result
JSON Output
{ name: "Alice", highScores: [92,95] }
{ name: "Cara", highScores: [100,99,98] }

1️⃣5️⃣ $reduce — Compute from Array

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 avgScore: {
5 $divide: [
6 { $reduce: {
7 input: "$scores",
8 initialValue: 0,
9 in: { $add: ["$$value", "$$this"] }
10 } },
11 { $size: "$scores" }
12 ]
13 }
14 } }
15]);
Query Result
JSON Output
{ name: "Alice", avgScore: 87.2 }
{ name: "Bob", avgScore: 74.33 }
{ name: "Cara", avgScore: 99 }

1️⃣6️⃣ $range — Generate Sequence

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: { name: 1, seq: { $range: [1, { $size: "$scores" }, 1] } } }
3]);
Query Result
JSON Output
{ name: "Alice", seq: [1,2,3,4,5] }

1️⃣7️⃣ $concatArrays — Merge Arrays

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 allTags: { $concatArrays: ["$tags", ["dev","db"]] }
5 } }
6]);
Query Result
JSON Output
{ name: "Alice", allTags: ["js","py","mongo","dev","db"] }

1️⃣8️⃣ $zip — Pair Arrays

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 paired: {
5 $zip: { inputs: ["$tags", ["junior","mid","senior"]], useLongestLength: true }
6 }
7 } }
8]);
Query Result
JSON Output
{ name: "Alice", paired: [["js","junior"],["py","mid"],["mongo","senior"]] }

1️⃣9️⃣ $arrayToObject — Convert Array → Object

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 statsDoc: {
5 $arrayToObject: [
6 ["count", { $size: "$scores" }],
7 ["best", { $max: "$scores" }]
8 ]
9 }
10 } }
11]);
Query Result
JSON Output
{ name: "Bob", statsDoc: { count: 3, best: 88 } }

2️⃣0️⃣ $objectToArray — Convert Object → Array

MongoDB Shell
NoSQL
Database
1db.studentsArr.aggregate([
2 { $project: {
3 name: 1,
4 statsArr: { $objectToArray: "$statsDoc" }
5 } }
6]);
Query Result
JSON Output
{ name: "Bob", statsArr: [{k:"count",v:3},{k:"best",v:88}] }
Keep Going!MongoDB - Type Operators