0% found this document useful (0 votes)
15 views23 pages

MongoDB Practical Exam - Complete Syntax Reference

This document provides a comprehensive reference for MongoDB syntax, covering basic database operations, collection operations, CRUD operations, query operators, aggregation pipeline stages, indexing, and bulk write operations. It includes detailed examples of commands for inserting, updating, deleting, and querying data, as well as advanced features like aggregation and array manipulation. The document serves as a practical guide for users to effectively utilize MongoDB's capabilities.

Uploaded by

Govind Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views23 pages

MongoDB Practical Exam - Complete Syntax Reference

This document provides a comprehensive reference for MongoDB syntax, covering basic database operations, collection operations, CRUD operations, query operators, aggregation pipeline stages, indexing, and bulk write operations. It includes detailed examples of commands for inserting, updating, deleting, and querying data, as well as advanced features like aggregation and array manipulation. The document serves as a practical guide for users to effectively utilize MongoDB's capabilities.

Uploaded by

Govind Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

MongoDB Practical Exam - Complete Syntax Reference

Basic Database Operations

Database Commands

javascript

// Show all databases


show dbs

// Switch to/create database


use database_name

// Show current database


db

// Drop database
db.dropDatabase()

Collection Operations

javascript

// Show collections
show collections

// Create collection
db.createCollection("collection_name")

// Drop collection
db.collection_name.drop()

CRUD Operations

Insert Operations

javascript
// Insert one document
db.collection_name.insertOne({field1: "value1", field2: "value2"})

// Insert multiple documents


db.collection_name.insertMany([
{field1: "value1", field2: "value2"},
{field1: "value3", field2: "value4"}
])

// Legacy insert (deprecated but still works)


db.collection_name.insert({field1: "value1"})

Find Operations

javascript

// Find all documents


db.collection_name.find()

// Find with condition


db.collection_name.find({field: "value"})

// Find one document


db.collection_name.findOne({field: "value"})

// Find with multiple conditions


db.collection_name.find({field1: "value1", field2: "value2"})

// Pretty print
db.collection_name.find().pretty()

// Limit results
db.collection_name.find().limit(5)

// Skip documents
db.collection_name.find().skip(10)

// Sort documents
db.collection_name.find().sort({field: 1}) // 1 for ascending, -1 for descending

// Count documents
db.collection_name.count()
db.collection_name.countDocuments({field: "value"})

Update Operations
javascript

// Update one document


db.collection_name.updateOne(
{field: "old_value"}, // filter
{$set: {field: "new_value"}} // update
)

// Update multiple documents


db.collection_name.updateMany(
{field: "old_value"},
{$set: {field: "new_value"}}
)

// Replace one document


db.collection_name.replaceOne(
{field: "value"},
{new_field1: "value1", new_field2: "value2"}
)

// Upsert (update or insert)


db.collection_name.updateOne(
{field: "value"},
{$set: {field: "new_value"}},
{upsert: true}
)

Delete Operations

javascript

// Delete one document


db.collection_name.deleteOne({field: "value"})

// Delete multiple documents


db.collection_name.deleteMany({field: "value"})

// Delete all documents


db.collection_name.deleteMany({})

Query Operators

Comparison Operators

javascript
// Equal
db.collection.find({field: {$eq: value}})

// Not equal
db.collection.find({field: {$ne: value}})

// Greater than
db.collection.find({field: {$gt: value}})

// Greater than or equal


db.collection.find({field: {$gte: value}})

// Less than
db.collection.find({field: {$lt: value}})

// Less than or equal


db.collection.find({field: {$lte: value}})

// In array
db.collection.find({field: {$in: [value1, value2, value3]}})

// Not in array
db.collection.find({field: {$nin: [value1, value2, value3]}}

Logical Operators

javascript

// AND (implicit)
db.collection.find({field1: "value1", field2: "value2"})

// AND (explicit)
db.collection.find({$and: [{field1: "value1"}, {field2: "value2"}]})

// OR
db.collection.find({$or: [{field1: "value1"}, {field2: "value2"}]})

// NOT
db.collection.find({field: {$not: {$eq: "value"}}})

// NOR
db.collection.find({$nor: [{field1: "value1"}, {field2: "value2"}]})

Element Operators

javascript
// Exists
db.collection.find({field: {$exists: true}})

// Type
db.collection.find({field: {$type: "string"}})

Array Operators

javascript

// All elements match


db.collection.find({array_field: {$all: ["value1", "value2"]}})

// Array size
db.collection.find({array_field: {$size: 3}})

// Element match
db.collection.find({array_field: {$elemMatch: {$gt: 10, $lt: 20}}})

Regular Expression

javascript

// Regex pattern
db.collection.find({field: {$regex: /pattern/}})
db.collection.find({field: {$regex: "pattern", $options: "i"}}) // case insensitive

Update Operators

Field Update Operators

javascript
// Set field value
{$set: {field: "new_value"}}

// Unset field
{$unset: {field: ""}}

// Increment numeric value


{$inc: {numeric_field: 5}}

// Multiply numeric value


{$mul: {numeric_field: 2}}

// Rename field
{$rename: {old_field_name: "new_field_name"}}

// Set minimum value


{$min: {field: value}}

// Set maximum value


{$max: {field: value}}

// Set current date


{$currentDate: {field: true}}
{$currentDate: {field: {$type: "timestamp"}}}

Array Update Operators

javascript
// Add to array
{$push: {array_field: "new_value"}}

// Add multiple to array


{$push: {array_field: {$each: ["value1", "value2"]}}}

// Add to set (unique)


{$addToSet: {array_field: "new_value"}}

// Remove from array


{$pull: {array_field: "value_to_remove"}}

// Remove multiple from array


{$pullAll: {array_field: ["value1", "value2"]}}

// Remove first/last element


{$pop: {array_field: 1}} // last element
{$pop: {array_field: -1}} // first element

Aggregation Pipeline

Basic Aggregation Syntax

javascript

db.collection.aggregate([
{stage1},
{stage2},
{stage3}
])

$match Stage

javascript

// Filter documents
{$match: {field: "value"}}
{$match: {field: {$gt: 100}}}
{$match: {$and: [{field1: "value1"}, {field2: {$gte: 50}}]}}

$project Stage

javascript
// Include/exclude fields
{$project: {field1: 1, field2: 1, _id: 0}}

// Rename fields
{$project: {new_name: "$old_field_name", field2: 1}}

// Create computed fields


{$project: {
field1: 1,
computed_field: {$add: ["$field2", "$field3"]},
full_name: {$concat: ["$first_name", " ", "$last_name"]}
}}

// Conditional projection
{$project: {
field1: 1,
status: {
$cond: {
if: {$gte: ["$score", 60]},
then: "Pass",
else: "Fail"
}
}
}}

$group Stage

javascript
// Basic grouping
{$group: {
_id: "$field_to_group_by",
count: {$sum: 1}
}}

// Multiple field grouping


{$group: {
_id: {field1: "$field1", field2: "$field2"},
total: {$sum: "$amount"}
}}

// Group all documents


{$group: {
_id: null,
total_count: {$sum: 1},
average: {$avg: "$field"}
}}

Group Accumulator Operators

javascript
// Sum
{$sum: "$field"}
{$sum: 1} // count

// Average
{$avg: "$field"}

// Minimum
{$min: "$field"}

// Maximum
{$max: "$field"}

// First
{$first: "$field"}

// Last
{$last: "$field"}

// Push to array
{$push: "$field"}

// Add to set (unique)


{$addToSet: "$field"}

$sort Stage

javascript

// Sort by one field


{$sort: {field: 1}} // ascending
{$sort: {field: -1}} // descending

// Sort by multiple fields


{$sort: {field1: 1, field2: -1}}

$limit and $skip Stages

javascript

// Limit results
{$limit: 10}

// Skip documents
{$skip: 5}
$unwind Stage

javascript

// Unwind array field


{$unwind: "$array_field"}

// Unwind with options


{$unwind: {
path: "$array_field",
includeArrayIndex: "array_index",
preserveNullAndEmptyArrays: true
}}

$lookup Stage (Join)

javascript

{$lookup: {
from: "other_collection",
localField: "local_field",
foreignField: "foreign_field",
as: "joined_data"
}}

$addFields Stage

javascript

{$addFields: {
new_field: {$add: ["$field1", "$field2"]},
computed_field: {$multiply: ["$quantity", "$price"]}
}}

Common Aggregation Examples

Example 1: Group and Count

javascript
db.orders.aggregate([
{$group: {
_id: "$customer_id",
total_orders: {$sum: 1},
total_amount: {$sum: "$amount"}
}}
])

Example 2: Match, Group, and Sort

javascript

db.sales.aggregate([
{$match: {date: {$gte: new Date("2024-01-01")}}},
{$group: {
_id: "$product",
total_sales: {$sum: "$quantity"},
avg_price: {$avg: "$price"}
}},
{$sort: {total_sales: -1}},
{$limit: 10}
])

Example 3: Complex Projection

javascript
db.students.aggregate([
{$project: {
name: 1,
total_marks: {$add: ["$math", "$science", "$english"]},
grade: {
$cond: {
if: {$gte: [{$add: ["$math", "$science", "$english"]}, 240]},
then: "A",
else: {
$cond: {
if: {$gte: [{$add: ["$math", "$science", "$english"]}, 180]},
then: "B",
else: "C"
}
}
}
}
}}
])

Indexing

Create Index

javascript

// Single field index


db.collection.createIndex({field: 1})

// Compound index
db.collection.createIndex({field1: 1, field2: -1})

// Text index
db.collection.createIndex({field: "text"})

// Unique index
db.collection.createIndex({field: 1}, {unique: true})

Index Operations

javascript
// List indexes
db.collection.getIndexes()

// Drop index
db.collection.dropIndex({field: 1})
db.collection.dropIndex("index_name")

// Drop all indexes


db.collection.dropIndexes()

Bulk Write Operations

Bulk Write Syntax

javascript

// Bulk write with array of operations


db.collection.bulkWrite([
{insertOne: {document: {field1: "value1", field2: "value2"}}},
{updateOne: {
filter: {field: "old_value"},
update: {$set: {field: "new_value"}},
upsert: true
}},
{updateMany: {
filter: {status: "inactive"},
update: {$set: {status: "active"}}
}},
{deleteOne: {filter: {field: "delete_me"}}},
{deleteMany: {filter: {status: "expired"}}},
{replaceOne: {
filter: {_id: ObjectId("...")},
replacement: {field1: "new_value1", field2: "new_value2"}
}}
], {ordered: false}) // ordered: true for sequential execution

Legacy Bulk Operations

javascript
// Unordered bulk operations
var bulk = db.collection.initializeUnorderedBulkOp();
bulk.insert({field1: "value1"});
bulk.find({field: "old"}).update({$set: {field: "new"}});
bulk.find({field: "delete_me"}).remove();
bulk.execute();

// Ordered bulk operations


var bulk = db.collection.initializeOrderedBulkOp();
bulk.insert({field1: "value1"});
bulk.find({field: "old"}).updateOne({$set: {field: "new"}});
bulk.find({field: "old"}).update({$set: {field: "new"}}); // updateMany
bulk.find({field: "delete_me"}).removeOne();
bulk.find({status: "expired"}).remove(); // removeMany
bulk.execute();

Advanced Aggregation Operators

$out Stage

javascript

// Write results to new collection


{$out: "new_collection_name"}

// Write to different database


{$out: {db: "other_database", coll: "collection_name"}}

// Example usage (must be last stage)


db.sales.aggregate([
{$group: {_id: "$product", total: {$sum: "$amount"}}},
{$sort: {total: -1}},
{$out: "product_totals"}
])

$sample Stage

javascript
// Get random sample of documents
{$sample: {size: 10}} // Get 10 random documents

// Example
db.products.aggregate([
{$sample: {size: 5}},
{$project: {name: 1, price: 1}}
])

String Operators

$concat

javascript

// Concatenate strings
{$concat: ["$first_name", " ", "$last_name"]}
{$concat: ["Hello ", "$name", "!"]}

// Example in projection
{$project: {
full_name: {$concat: ["$first_name", " ", "$last_name"]},
email_domain: {$concat: ["@", "$company", ".com"]}
}}

$dateToString

javascript
// Convert date to string
{$dateToString: {format: "%Y-%m-%d", date: "$date_field"}}
{$dateToString: {format: "%d/%m/%Y %H:%M", date: "$created_at"}}

// Common format specifiers:


// %Y - 4-digit year
// %m - Month (01-12)
// %d - Day (01-31)
// %H - Hour (00-23)
// %M - Minute (00-59)
// %S - Second (00-59)

// Example
{$project: {
name: 1,
formatted_date: {$dateToString: {
format: "%d-%m-%Y",
date: "$birth_date"
}}
}}

Array Operators

$arrayElemAt

javascript

// Get element at specific index


{$arrayElemAt: ["$array_field", 0]} // first element
{$arrayElemAt: ["$array_field", -1]} // last element
{$arrayElemAt: ["$array_field", 2]} // third element

// Example
{$project: {
name: 1,
first_score: {$arrayElemAt: ["$scores", 0]},
last_score: {$arrayElemAt: ["$scores", -1]}
}}

$slice

javascript
// Get subset of array
{$slice: ["$array_field", 3]} // first 3 elements
{$slice: ["$array_field", -2]} // last 2 elements
{$slice: ["$array_field", 1, 3]} // skip 1, take 3
{$slice: ["$array_field", -5, 2]} // from 5th last, take 2

// Example
{$project: {
name: 1,
top_3_scores: {$slice: ["$scores", 3]},
recent_activities: {$slice: ["$activities", -5]}
}}

Advanced $push with $each and $position

javascript
// Add multiple elements to array
{$push: {
array_field: {
$each: ["value1", "value2", "value3"]
}
}}

// Add at specific position


{$push: {
array_field: {
$each: ["new_value"],
$position: 0 // insert at beginning
}
}}

// Add with position and slice (keep only certain number)


{$push: {
array_field: {
$each: ["new_value"],
$position: 0,
$slice: 5 // keep only first 5 elements
}
}}

// Add with sort


{$push: {
scores: {
$each: [85, 92],
$sort: -1 // sort in descending order
}
}}

// Complete example
db.students.updateOne(
{_id: ObjectId("...")},
{$push: {
scores: {
$each: [95, 87, 91],
$sort: -1,
$slice: 10 // keep top 10 scores only
}
}}
)

More Array Update Operators


$pullAll with conditions

javascript

// Remove all matching elements


{$pullAll: {array_field: ["value1", "value2", "value3"]}}

// Pull with condition


{$pull: {
scores: {$lt: 60} // remove all scores less than 60
}}

// Pull from array of objects


{$pull: {
items: {status: "inactive"}
}}

$addToSet with $each

javascript

// Add multiple unique elements


{$addToSet: {
tags: {$each: ["tag1", "tag2", "tag3"]}
}}

Complete Examples with New Operators

Example 1: Using $out and $sample

javascript

db.customers.aggregate([
{$sample: {size: 1000}}, // Get random sample
{$match: {status: "active"}},
{$group: {
_id: "$region",
avg_age: {$avg: "$age"},
total_customers: {$sum: 1}
}},
{$out: "customer_analytics"} // Save to new collection
])

Example 2: String and Date Operations

javascript
db.employees.aggregate([
{$project: {
full_name: {$concat: ["$first_name", " ", "$last_name"]},
hire_date_formatted: {$dateToString: {
format: "%d-%m-%Y",
date: "$hire_date"
}},
first_skill: {$arrayElemAt: ["$skills", 0]},
recent_projects: {$slice: ["$projects", -3]}
}}
])

Example 3: Complex Array Operations

javascript

// Update with position and each


db.products.updateMany(
{category: "electronics"},
{$push: {
reviews: {
$each: [
{rating: 5, comment: "Excellent!"},
{rating: 4, comment: "Good product"}
],
$position: 0, // Add at beginning
$slice: 20 // Keep only latest 20 reviews
}
}}
)

Example 4: Bulk Write with Mixed Operations

javascript
db.inventory.bulkWrite([
{insertOne: {
document: {
product: "New Item",
quantity: 100,
tags: ["new", "featured"]
}
}},
{updateMany: {
filter: {quantity: {$lt: 10}},
update: {
$set: {status: "low_stock"},
$push: {
alerts: {
$each: [{
type: "low_stock",
date: new Date(),
message: "Quantity below threshold"
}],
$position: 0,
$slice: 5
}
}
}
}},
{deleteMany: {
filter: {
status: "discontinued",
last_sold: {$lt: new Date("2023-01-01")}
}
}}
], {ordered: false})

Additional Useful Operations

Explain Query

javascript

db.collection.find({field: "value"}).explain()
db.collection.find({field: "value"}).explain("executionStats")

Tips for Exam Success


1. Always use pretty() for readable output: db.collection.find().pretty()
2. Remember aggregation pipeline order matters

3. Use $match early in aggregation to filter data

4. Practice complex $group operations with multiple accumulators


5. Know the difference between find() and aggregate()

6. Remember projection syntax: 1 to include, 0 to exclude


7. Use proper data types in queries (strings need quotes, numbers don't)
8. Test your queries step by step in complex aggregations

You might also like