Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
206 changes: 206 additions & 0 deletions mongodb/examples/aggregate-js-functions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
// $function operator - custom JavaScript functions in aggregation
// The JavaScript code is passed as a string in the "body" field

// Basic $function usage
db.players.aggregate([
{ $addFields: {
isFound: {
$function: {
body: "function(name) { return name.length > 5; }",
args: ["$name"],
lang: "js"
}
}
}}
])

// $function with multiple arguments
db.orders.aggregate([
{ $addFields: {
discount: {
$function: {
body: "function(price, quantity) { return price * quantity * 0.1; }",
args: ["$price", "$quantity"],
lang: "js"
}
}
}}
])

// $function with complex logic
db.events.aggregate([
{ $addFields: {
category: {
$function: {
body: "function(score) { if (score >= 90) return 'A'; else if (score >= 80) return 'B'; else if (score >= 70) return 'C'; else return 'F'; }",
args: ["$score"],
lang: "js"
}
}
}}
])

// $function with no arguments
db.items.aggregate([
{ $addFields: {
timestamp: {
$function: {
body: "function() { return new Date().toISOString(); }",
args: [],
lang: "js"
}
}
}}
])

// $function with array argument
db.data.aggregate([
{ $addFields: {
processed: {
$function: {
body: "function(arr) { return arr.map(x => x * 2); }",
args: ["$values"],
lang: "js"
}
}
}}
])

// $function with multiline string (escaped)
db.documents.aggregate([
{ $addFields: {
result: {
$function: {
body: "function(doc) {\n var sum = 0;\n for (var i = 0; i < doc.length; i++) {\n sum += doc[i];\n }\n return sum;\n}",
args: ["$numbers"],
lang: "js"
}
}
}}
])

// $accumulator operator - custom accumulator with JavaScript
db.sales.aggregate([
{ $group: {
_id: "$category",
customSum: {
$accumulator: {
init: "function() { return { sum: 0, count: 0 }; }",
accumulate: "function(state, value) { return { sum: state.sum + value, count: state.count + 1 }; }",
accumulateArgs: ["$amount"],
merge: "function(state1, state2) { return { sum: state1.sum + state2.sum, count: state1.count + state2.count }; }",
finalize: "function(state) { return state.sum / state.count; }",
lang: "js"
}
}
}}
])

// $accumulator with initArgs
db.transactions.aggregate([
{ $group: {
_id: "$accountId",
balance: {
$accumulator: {
init: "function(initial) { return initial; }",
initArgs: [0],
accumulate: "function(state, amount, type) { return type === 'credit' ? state + amount : state - amount; }",
accumulateArgs: ["$amount", "$type"],
merge: "function(s1, s2) { return s1 + s2; }",
lang: "js"
}
}
}}
])

// $accumulator without finalize
db.metrics.aggregate([
{ $group: {
_id: "$source",
values: {
$accumulator: {
init: "function() { return []; }",
accumulate: "function(state, val) { state.push(val); return state; }",
accumulateArgs: ["$value"],
merge: "function(s1, s2) { return s1.concat(s2); }",
lang: "js"
}
}
}}
])

// Combined $function and standard operators
db.products.aggregate([
{ $match: { inStock: true } },
{ $addFields: {
priceCategory: {
$function: {
body: "function(p) { return p < 10 ? 'cheap' : p < 100 ? 'moderate' : 'expensive'; }",
args: ["$price"],
lang: "js"
}
}
}},
{ $group: { _id: "$priceCategory", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])

// $function in $project stage
db.users.aggregate([
{ $project: {
name: 1,
maskedEmail: {
$function: {
body: "function(email) { var parts = email.split('@'); return parts[0].substring(0, 2) + '***@' + parts[1]; }",
args: ["$email"],
lang: "js"
}
}
}}
])

// $function with object argument
db.records.aggregate([
{ $addFields: {
serialized: {
$function: {
body: "function(obj) { return JSON.stringify(obj); }",
args: ["$metadata"],
lang: "js"
}
}
}}
])

// $function returning object
db.coordinates.aggregate([
{ $addFields: {
point: {
$function: {
body: "function(lat, lng) { return { type: 'Point', coordinates: [lng, lat] }; }",
args: ["$latitude", "$longitude"],
lang: "js"
}
}
}}
])

// Nested $function in $facet
db.analytics.aggregate([
{ $facet: {
processed: [
{ $addFields: {
normalized: {
$function: {
body: "function(v, min, max) { return (v - min) / (max - min); }",
args: ["$value", "$minValue", "$maxValue"],
lang: "js"
}
}
}}
],
summary: [
{ $group: { _id: null, total: { $sum: "$value" } } }
]
}}
])
103 changes: 103 additions & 0 deletions mongodb/examples/unicode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Unicode support - emoji characters
db.posts.find({ reaction: "👍" })
db.posts.find({ emoji: "🎉🎊🎁" })
db.posts.insertOne({ title: "Hello 🌍", content: "Testing emoji support 😀" })
db.messages.updateOne({ _id: 1 }, { $set: { status: "✅ completed" } })

// Unicode - emoji in field names (quoted)
db.reactions.find({ "👍": { $gt: 10 } })
db.reactions.insertOne({ "👍": 100, "👎": 5, "❤️": 50 })

// Unicode - Hindi (Devanagari script)
db.users.find({ name: "नमस्ते" })
db.users.find({ greeting: "आपका स्वागत है" })
db.products.insertOne({ name: "चाय", description: "भारतीय मसाला चाय" })
db.articles.find({ title: "हिंदी में लेख" })

// Unicode - Chinese (Simplified)
db.users.find({ name: "你好世界" })
db.products.find({ category: "电子产品" })
db.orders.insertOne({ item: "笔记本电脑", price: 5999 })

// Unicode - Chinese (Traditional)
db.users.find({ name: "繁體中文" })
db.products.find({ description: "傳統工藝品" })

// Unicode - Japanese (Hiragana, Katakana, Kanji)
db.users.find({ greeting: "こんにちは" })
db.products.find({ name: "カタカナ" })
db.articles.find({ title: "日本語の記事" })

// Unicode - Korean
db.users.find({ name: "안녕하세요" })
db.products.find({ category: "한국 음식" })

// Unicode - Arabic (right-to-left)
db.users.find({ name: "مرحبا بالعالم" })
db.articles.find({ title: "مقال باللغة العربية" })

// Unicode - Thai
db.users.find({ greeting: "สวัสดี" })
db.products.find({ name: "อาหารไทย" })

// Unicode - Russian (Cyrillic)
db.users.find({ name: "Привет мир" })
db.articles.find({ title: "Русский текст" })

// Unicode - Greek
db.users.find({ name: "Γειά σου κόσμε" })
db.math.find({ symbol: "π", value: 3.14159 })

// Unicode - Hebrew
db.users.find({ greeting: "שלום עולם" })

// Unicode - mixed scripts in single document
db.international.insertOne({
english: "Hello",
hindi: "नमस्ते",
chinese: "你好",
japanese: "こんにちは",
korean: "안녕하세요",
arabic: "مرحبا",
russian: "Привет",
emoji: "👋🌍"
})

// Unicode - special characters and symbols
db.math.find({ formula: "∑∏∫∂√∞" })
db.currency.find({ symbols: "€£¥₹₽₿" })
db.symbols.find({ arrows: "←→↑↓↔↕" })
db.music.find({ notes: "♪♫♬♩" })

// Unicode - combining characters and diacritics
db.users.find({ name: "José García" })
db.users.find({ name: "François Müller" })
db.users.find({ name: "Søren Kierkegaard" })
db.users.find({ name: "Nguyễn Văn A" })

// Unicode in aggregation pipelines
db.posts.aggregate([
{ $match: { reaction: "👍" } },
{ $group: { _id: "$emoji", count: { $sum: 1 } } }
])

db.international.aggregate([
{ $project: { greeting: { $concat: ["Hello ", "$hindi", " ", "$emoji"] } } }
])

// Unicode in array values
db.tags.find({ labels: { $in: ["重要", "紧急", "🔥"] } })
db.posts.insertOne({ tags: ["日本語", "한국어", "中文", "हिंदी"] })

// Unicode escape sequences (existing support)
db.users.find({ escaped: "\u0048\u0065\u006C\u006C\u006F" })
db.users.find({ mixed: "Hello \u4E16\u754C" })

// Unicode in regex patterns
db.articles.find({ title: /नमस्ते/ })
db.products.find({ name: /^你好/ })

// Unicode in index and collection names (via bracket notation)
db["文章"].find({})
db["статьи"].insertOne({ title: "Тест" })
db["記事"].aggregate([{ $match: { published: true } }])
Loading