0% found this document useful (0 votes)
33 views17 pages

MongoDB Commands and Query Techniques

The document provides a comprehensive guide on using MongoDB, covering commands for database management, data insertion, querying, and aggregation. It includes details on various operators, methods for updating and deleting data, and advanced features like validation, indexing, and aggregation pipelines. Additionally, it explains the use of different data types and operators for effective data manipulation.
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)
33 views17 pages

MongoDB Commands and Query Techniques

The document provides a comprehensive guide on using MongoDB, covering commands for database management, data insertion, querying, and aggregation. It includes details on various operators, methods for updating and deleting data, and advanced features like validation, indexing, and aggregation pipelines. Additionally, it explains the use of different data types and operators for effective data manipulation.
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

# Start MONGODB

mongosh

# Check All Databases


show dbs

# Create And Use Database


use database_Name

# Check current database


db

# Create Collection
[Link]("database_name")

# Check collections
show collections

# Change collection name


db.old_name.renameCollection("new Name")

# For help
[Link]()
db.collection_Name.help()
# Delete any collection and database
db.collection_name.drop()
use databasename
[Link]()

# Insert data into database


db.collection_name.insertOne({field1: "value", field2: "value"})

db.collection_name.insertMany([
{field1: "value", field2: "value"},
{field1: "value", field2: "value"}
])

# Different types of data


db.collection_name.insertOne({
Name: "Rahul", // String
age: 25, // Integer
married: true, // Boolean
dob: ISODate("2000-10-15T[Link].000Z"), // Date
forCurrentDate: new Date(), // Current Date
weight: 72.7, // Double
kids: null, // Null
hobbies: ["Dance", "Cooking"], // Array
address: { street: "Yusufpur road" } // Object
})

# Set validation for a new collection


[Link]("collection_Name", {
validator: {
$jsonSchema: {
properties: {
name: {
bsonType: "string",
description: "Name must be in string"
},
age: {
bsonType: "int",
description: "Age must be in integer"
}
}
}
}
})

# Set validation on existing collection


[Link]({
collMod: "Collection_Name",
validator: {
$jsonSchema: {
properties: {
name: {
bsonType: "string",
description: "Name must be in string"
},
age: {
bsonType: "int",
description: "Age must be in integer"
}
}
}
}
})

# Update and replace data in collection


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

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

# Methods: $set, $inc, $mul, $rename, $currentDate, $min, $max


# For Arrays: $push, $addToSet, $pop, $pull, $pullAll

# Delete data from collection


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

# Find data from collection


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

# Methods used with find


db.collection_name.find({field: "value"}).projection({field1: 1, field2: 0})
db.collection_name.find({field: "value"}).count()
db.collection_name.find({field: "value"}).sort({field: 1})
db.collection_name.find({field: "value"}).limit(value)
db.collection_name.find({field: "value"}).limit(value).skip(value)

# Comparison operators (used with find/update/delete)


db.collection_name.find({field: {$eq: value}})
$eq - Equal to
$ne - Not equal to
$gt - Greater than
$gte - Greater than or equal to
$lt - Less than
$lte - Less than or equal to
$in - Match value in array
$nin - Not match in array

# Logical operators
db.collection_name.find({$and: [{field1: "value"}, {field2: "value"}]})
db.collection_name.find({$or: [{field1: "value"}, {field2: "value"}]})
db.collection_name.find({$nor: [{field1: "value"}, {field2: "value"}]})
db.collection_name.find({field: {$not: "value"}})

# Element operators
db.collection_name.find({field: {$exists: true/false}})
db.collection_name.find({field: {$type: "string"/"int"/etc}})

# MongoDB Query Operators


1. $regex – Regular Expression Matching
[Link]({name: {$regex: /^A/, $options: "i"}})
// Finds users whose name starts with "A", case-insensitive

2. $expr – Use aggregation expressions in queries


[Link]({$expr: {$gt: ["$quantity", "$threshold"]}})
// Finds documents where quantity > threshold

3. $jsonSchema – JSON Schema Validation


[Link]({
$jsonSchema: {
required: ["name", "price"],
properties: {
name: { bsonType: "string" },
price: { bsonType: "number", minimum: 0 }
}
}
})
// Finds products with valid schema

4. $mod – Modulo Operation


[Link]({value: {$mod: [5, 0]}})
// Finds numbers divisible by 5
1. findOneAndUpdate()
Purpose: Finds a document and updates it.

[Link](
{ _id: 1 }, // Filter
{ $set: { name: "Alice" } }, // Update
{ returnDocument: "after" } // Options: "before" (default) or "after"
);
Options:
returnDocument: "before" or "after"
upsert: true to insert if not found
sort: sort order if multiple docs match
projection: limit returned fields

2. findOneAndReplace()
Purpose: Finds a document and replaces it entirely with a new document.

[Link](
{ username: "bob" }, // Filter
{ username: "bob", age: 30 }, // Replacement document
{ returnDocument: "after" }
);
Notes:
Replacement document must include all fields (not just updates).

3. findOneAndDelete()
Purpose: Finds a document and deletes it.
[Link](
{ email: "user@[Link]" } // Filter
);
Notes:
Always returns the deleted document, if found.

#Aggregation Pipeline Stages ($stage operators)


| Operator | Description |
| -------------- | -------------------------------------------------------------- |
| `$match` | Filters documents (like a query) |
| `$project` | Selects and reshapes fields |
| `$group` | Groups documents (like SQL `GROUP BY`) |
| `$sort` | Sorts documents |
| `$limit` | Limits number of documents |
| `$skip` | Skips N documents |
| `$unwind` | Deconstructs an array field |
| `$lookup` | Performs a left outer join with another collection |
| `$facet` | Runs multiple pipelines in parallel |
| `$bucket` | Categorizes into buckets by ranges |
| `$bucketAuto` | Auto-categorizes into buckets |
| `$count` | Counts documents |
| `$replaceRoot` | Replaces the input document with a specified embedded document |
| `$replaceWith` | Same as `$replaceRoot` (alias) |
| `$merge` | Writes the result into a collection |
| `$out` | Replaces an entire collection |
| `$addFields` | Adds new fields to documents |
| `$set` | Alias for `$addFields` |
| `$unset` | Removes fields |
| `$project` | Includes/excludes fields |
| `$sortByCount` | Groups by value and counts |

{example [Link]([ {$match:{ age: { $gte: 18 } } },{$sort:{age:1}},{$project:{name:1,age:1}}])

# Accumulator Operators (used in $group)


| Operator | Description |
| --------------- | ---------------------------------------------------- |
| `$sum` | Adds numeric values for the group |
| `$avg` | Computes average of numeric values |
| `$min` | Returns minimum value |
| `$max` | Returns maximum value |
| `$first` | Returns the first document's value in the group |
| `$last` | Returns the last document's value in the group |
| `$push` | Appends values to an array |
| `$addToSet` | Adds unique values to an array (no duplicates) |
| `$mergeObjects` | Merges documents (fields) into one |
| `$stdDevPop` | Population standard deviation |
| `$stdDevSamp` | Sample standard deviation |
| `$count` | Shortcut to count documents (used outside `$group`) |
| `$accumulator` | Custom aggregation logic using JavaScript (advanced) |

[Link]([
{
$group: {
_id: "$userId", // make group using userid
lastLogin: { $last: "$loginTime" }
}
}
])
# $lookup – MongoDB Join Operator {$lookup operator ek document ko doosri collection ke document(s) ke saath join karta hai based on
common field(s).}

orders: document1

{
_id: 1,
customerId: 101,
item: "Laptop"
}

customers: document2

{
_id: 101,
name: "Amit",
city: "Delhi"
}

[Link]([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
}
}
])

# bucket and bucket auto operator

| Feature | `$bucket` | `$bucketAuto` |


| --------------- | ---------------------------------------- | ------------------------------------- |
| Buckets defined | **Manually (boundaries)** | **Automatically calculated** |
| Flexibility | Full control over bucket ranges | No need to define ranges |
| Output | Buckets with counts (and optional stats) | Same, but bucket ranges are generated |

{
$bucket: {
groupBy: "<field>",
boundaries: [ <low>, <mid1>, <mid2>, <high> ],
default: "Other", // Optional bucket for unmatched values
output: {
count: { $sum: 1 },
items: { $push: "$$ROOT" }
}
}
}

{
$bucketAuto: {
groupBy: "<field>",
buckets: <number>,
output: {
count: { $sum: 1 }
}
}
}

#$addFields – Add or Modify Fields


Document mein naye field add karne ke liye

Ya existing field ko modify karne ke liye


{
$addFields: {
newField: <expression>,
existingField: <newValue>
}
}

#$unwind – Flatten Array Fields


Array field ko explode karta hai — ek document se multiple bana deta hai

{
$unwind: {
path: "$arrayField",
preserveNullAndEmptyArrays: true // optional
}
}

#$out – Replace Entire Collection


Aggregation result ko ek new ya existing collection mein overwrite kar deta hai.
[Link]([
{ $match: { status: "confirmed" } },
{ $out: "confirmed_orders" }
])

#$merge – Insert/Update into Collection (Safe Version of $out)


Aggregation result ko merge, insert, replace karein kisi existing collection ke saath.
{
$merge: {
into: "collection_name",
on: "_id", // optional matching field(s)
whenMatched: "merge", // or "replace", "keepExisting", "fail"
whenNotMatched: "insert" // or "discard", "fail"
}
}

#$unionWith – Combine Data from Another Collection


Ek pipeline mein do collections ka data combine karo (like SQL UNION).
db.active_users.aggregate([
{
$unionWith: {
coll: "inactive_users",
pipeline: [ { $project: { name: 1, email: 1 } } ]
}
}
])

#Arithmetic Operators
| Operator | Description | Example |
| ----------- | ---------------------- | ----------------------------------- |
| `$add` | Add numbers or dates | `{ $add: ["$price", "$tax"] }` |
| `$subtract` | Subtract numbers/dates | `{ $subtract: ["$end", "$start"] }` |
| `$multiply` | Multiply values | `{ $multiply: ["$price", 0.18] }` |
| `$divide` | Divide values | `{ $divide: ["$total", "$count"] }` |
| `$mod` | Modulus | `{ $mod: [10, 3] }` `1` |

2. String Operators
| Operator | Description | Example |
| ------------------ | ------------------------- | --------------------------------------- |
| `$concat` | Concatenate strings | `{ $concat: ["$first", " ", "$last"] }` |
| `$substr` | Substring | `{ $substr: ["$name", 0, 3] }` |
| `$substrBytes` | Byte-wise substring | `{ $substrBytes: ["$name", 0, 2] }` |
| `$substrCP` | Codepoint-wise substring | `{ $substrCP: ["$emoji", 0, 1] }` |
| `$toLower` | Convert to lowercase | `{ $toLower: "$name" }` |
| `$toUpper` | Convert to uppercase | `{ $toUpper: "$city" }` |
| `$trim` | Trim spaces or characters | `{ $trim: { input: "$name" } }` |
| `$ltrim`, `$rtrim` | Trim from left/right | |
| `$strLenBytes` | Length in bytes | `{ $strLenBytes: "$name" }` |
| `$strLenCP` | Length in codepoints | `{ $strLenCP: "$name" }` |

3. Date Operators
| Operator | Description | Example |
| -------------------------------- | -------------------------- | --------------------------------------------------------------- |
| `$dateToString` | Format date to string | `{ $dateToString: { format: "%Y-%m", date: "$createdAt" } }` |
| `$dayOfWeek` | 1 (Sunday) to 7 (Saturday) | `{ $dayOfWeek: "$date" }` |
| `$year`, `$month`, `$dayOfMonth` | Extract parts | `{ $year: "$createdAt" }` |
| `$hour`, `$minute`, `$second` | Extract time | `{ $hour: "$createdAt" }` |
| `$dateAdd`, `$dateSubtract` | Add/subtract time | `{ $dateAdd: { startDate: "$start", unit: "day", amount: 7 } }` |
| `$isoWeek`, `$isoWeekYear` | ISO weeks | |

4. Array Operators
| Operator | Description | Example |
| ----------------- | ---------------------------- | --------------------------------------- |
| `$size` | Length of array | `{ $size: "$hobbies" }` |
| `$arrayElemAt` | Get element by index | `{ $arrayElemAt: ["$hobbies", 0] }` |
| `$concatArrays` | Join arrays | `{ $concatArrays: ["$arr1", "$arr2"] }` |
| `$filter` | Filter elements from array | `filter items where score > 80` |
| `$map` | Transform each element | Add prefix etc. |
| `$in` | Check if value in array | `{ $in: ["Math", "$subjects"] }` |
| `$indexOfArray` | Find index | `{ $indexOfArray: ["$arr", "x"] }` |
| `$slice` | Get portion of array | `{ $slice: ["$arr", 3] }` |
| `$first`, `$last` | Get first/last array element | `{ $first: "$hobbies" }` |

5. Type Operators
| Operator | Description | Example |
| -------------------------------------- | ----------------------------- | ------------------------------------------------- |
| `$type` | Return data type of field | `{ $type: "$amount" }` |
| `$convert` | Convert between types | `{ $convert: { input: "$price", to: "string" } }` |
| `$toString`, `$toInt`, `$toBool`, etc. | Shortcuts | `{ $toString: "$_id" }` |
| `$isNumber` | Check if numeric (MongoDB 7+) | `{ $isNumber: "$value" }` |

6. Conditional Operators
| Operator | Description | Example |
| ------------------------------------------ | ---------------------- | -------------------------------------------------------- |
| `$cond` | If-then-else | `{ $cond: [ { $gt: ["$marks", 40] }, "Pass", "Fail" ] }` |
| `$ifNull` | Return default if null | `{ $ifNull: ["$nickname", "Guest"] }` |
| `$switch` | Multiple case-when | Advanced if-else ladder |
| `$eq`, `$ne`, `$gt`, `$lt`, `$gte`, `$lte` | Comparisons | `{ $eq: ["$a", "$b"] }` |

You might also like