Skip to content

Instantly share code, notes, and snippets.

@mutairibassam
Created June 16, 2023 10:54
Show Gist options
  • Save mutairibassam/f41c472d2f85d0d37e46e176d1b7bb1c to your computer and use it in GitHub Desktop.
Save mutairibassam/f41c472d2f85d0d37e46e176d1b7bb1c to your computer and use it in GitHub Desktop.
const pipeline_using_match_group = [
// Stage 1: match the accounts with a balance greater than $1,000
{ $match: { balance: { $lt: 1000 } } },
// Stage 2: Calculate average balance and total balance
{
$group: {
_id: "$account_type",
total_balance: { $sum: "$balance" },
avg_balance: { $avg: "$balance" },
},
},
]
const pipeline_using_match_sort_project = [
// Stage 1: $match - filter the documents (checking, balance >= 1500)
{ $match: { account_type: "checking", balance: { $gte: 1500 } } },
// Stage 2: $sort - sorts the documents in descending order (balance)
{ $sort: { balance: -1 } },
// Stage 3: $project - project only the requested fields and one computed field (account_type, account_id, balance, gbp_balance)
{
$project: {
_id: 0,
account_id: 1,
account_type: 1,
balance: 1,
// GBP stands for Great British Pound
gbp_balance: { $divide: ["$balance", 1.3] },
},
},
]
// A session allows you to perform multiple operations on MongoDB documents and collections
// while ensuring data consistency and atomicity.
const session = db.getMongo().startSession()
session.startTransaction()
const account = session.getDatabase('< add database name here>').getCollection('<add collection name here>')
// Add database operations like .updateOne() here
session.commitTransaction() // or
session.abortTransaction()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment