مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD
سينشئ المتعلمون مشغل قاعدة بيانات يعمل عند أحداث الإدراج أو التحديث، ويشغّل Atlas Function لمزامنة البيانات أو إرسال إشعار.
مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD درس مجاني في MongoDB Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في MongoDB Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة MongoDB Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
What Are Atlas Database Triggers?
Atlas Database Triggers are serverless event handlers that automatically execute an Atlas Function whenever a specific CRUD event (insert, update, replace, delete) occurs on a collection. They are built on top of MongoDB Change Streams and eliminate the need to run a polling process or manage infrastructure for event-driven workflows.
How Triggers Work Under the Hood
Internally, Atlas triggers use a change stream that MongoDB opens on the target collection. Every matching change event is forwarded to the trigger, which invokes the associated Atlas Function with the event document as its argument. The function runs in Atlas's managed JavaScript runtime — no servers to provision or scale. Triggers can handle up to hundreds of events per second with auto-scaling.
Creating a Trigger: Key Configuration
When configuring a database trigger you specify: Cluster name and collection to watch. Operation types to react to: insert, update, replace, delete, or any combination. Full Document option — when enabled, MongoDB fetches the complete document after the change and includes it in the event payload. Linked Function — the Atlas Function to invoke.
// Trigger configuration (set in Atlas UI or App Services API)
// {
// name: 'onOrderInsert',
// type: 'DATABASE',
// config: {
// serviceId: '...',
// database: 'mydb',
// collection: 'orders',
// operationTypes: ['INSERT'],
// fullDocument: true
// },
// functionName: 'handleNewOrder'
// }The Change Event Document
The event document passed to the trigger function has these key fields: operationType ('insert', 'update', 'replace', 'delete'), fullDocument (the document after the change, if enabled), documentKey (the _id of the changed document), updateDescription (for updates: which fields were set or unset), and ns (database and collection namespace).
// Example change event passed to the trigger function:
// {
// operationType: 'INSERT',
// fullDocument: { _id: ObjectId('...'), item: 'laptop', qty: 1, status: 'pending' },
// documentKey: { _id: ObjectId('...') },
// ns: { db: 'mydb', coll: 'orders' },
// clusterTime: Timestamp(...)
// }Writing a Trigger Function: New Order Handler
A trigger function is an Atlas Function — server-side JavaScript that has access to the context object (MongoDB client, services, user info) and receives the change event as its first argument. Here is a pattern for handling new orders: send a notification email and update an analytics counter.
// Atlas Function: handleNewOrder
exports = async function(changeEvent) {
const order = changeEvent.fullDocument
if (!order) return // safeguard if fullDocument is null
const db = context.services.get('mongodb-atlas').db('mydb')
// Update daily order count
await db.collection('daily_stats').updateOne(
{ date: new Date().toISOString().split('T')[0] },
{ $inc: { orderCount: 1, revenue: order.amount || 0 } },
{ upsert: true }
)
// Send notification (using a linked email service)
await context.services.get('myEmailService').send({
to: 'ops@company.com',
subject: 'New order: ' + order._id,
body: 'Amount: ' + order.amount
})
}Filtering Trigger Events
You can add a match expression to a trigger so it only fires for a subset of events. This is implemented as an aggregation pipeline on the change stream. For example, only trigger on orders above a certain amount, only fire on updates where the status field changed, or only react to documents from a specific tenant.
// Trigger match filter (aggregation pipeline on the change stream)
// Only fire the trigger when order amount > 500
// {
// 'match': {
// 'fullDocument.amount': { '$gt': 500 },
// 'operationType': 'INSERT'
// }
// }
// Only fire when 'status' field is part of the update
// {
// 'match': {
// 'updateDescription.updatedFields.status': { '$exists': true }
// }
// }Full Document vs Update Lookup
For INSERT and REPLACE operations, fullDocument is always available in the change event. For UPDATE events, fullDocument is only available if you enable the Full Document option in the trigger config, which causes Atlas to perform an additional document lookup (a second read). Without it, only updateDescription (changed fields) is available.
// Trigger function handling UPDATE events
exports = async function(changeEvent) {
const { operationType, updateDescription, fullDocument, documentKey } = changeEvent
if (operationType === 'UPDATE') {
const updatedFields = updateDescription.updatedFields
// Only process if 'status' was updated to 'shipped'
if (updatedFields.status === 'shipped') {
// Notify customer using documentKey._id to fetch full data
const db = context.services.get('mongodb-atlas').db('mydb')
const order = fullDocument || await db.collection('orders').findOne({ _id: documentKey._id })
// ... send shipment notification
}
}
}Error Handling and Retry in Triggers
If a trigger function throws an error or times out (maximum 90 seconds), Atlas automatically retries it up to 3 times with exponential backoff. After all retries fail, the event is logged as failed in the Atlas Trigger error log. You should write trigger functions to be idempotent — applying the function multiple times to the same event produces the same result — to handle retries safely.
// Idempotent trigger: use upsert to avoid duplicate stats on retry
exports = async function(changeEvent) {
const order = changeEvent.fullDocument
const db = context.services.get('mongodb-atlas').db('mydb')
// Upsert is safe to retry: same result whether run once or five times
await db.collection('order_summaries').updateOne(
{ _id: order._id }, // dedup key = original document _id
{ $set: { status: order.status, amount: order.amount, processedAt: new Date() } },
{ upsert: true }
)
}Cascading Triggers: Data Sync Pattern
A common use case is data synchronisation: when a document changes in one collection, a trigger propagates the change to a denormalised copy in another collection. For example, when a user's email changes in the users collection, a trigger updates the denormalised email field in every document in the orders collection that references that user.
// Sync user email to orders whenever user is updated
exports = async function(changeEvent) {
const updated = changeEvent.updateDescription.updatedFields
if (!updated.email) return // email didn't change, skip
const userId = changeEvent.documentKey._id
const db = context.services.get('mongodb-atlas').db('mydb')
await db.collection('orders').updateMany(
{ userId: userId },
{ $set: { userEmail: updated.email } }
)
}Trigger Ordering and Concurrency
By default, Atlas triggers process events sequentially in the order they arrive. If you enable event ordering off (in trigger settings), multiple function invocations can run in parallel for higher throughput — but then your function must be safe for concurrent execution. Sequential mode is safer; parallel mode is faster for high-event-rate collections.
Disabling and Monitoring Triggers
You can enable or disable triggers at any time from the Atlas UI without deleting them. The Trigger Execution Log in Atlas shows each invocation: status (success/failure/timeout), duration, and error details. Use this log to debug failing triggers and monitor execution trends. Atlas also exposes trigger metrics in the Atlas Monitoring dashboard.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: Atlas Database Triggers fire an Atlas Function on insert/update/replace/delete events using a change stream internally, match expressions filter which events invoke the function, and functions must be idempotent because Atlas retries failed invocations automatically. Next up we explore scheduled triggers and cron jobs.
تعلم JavaScript مع معلم ذكاء اصطناعي — مجانًا
اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.
- الدورات
- 30
- الدروس
- 120
الأسئلة الشائعة
هل درس «مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD» مجاني؟
نعم — نص درس «مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة MongoDB Academy، انتقل إلى CoddyKit PRO. تتضمن دورة MongoDB Academy 4 دروس في المجموع.
ماذا ستتعلم في «مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD»؟
سينشئ المتعلمون مشغل قاعدة بيانات يعمل عند أحداث الإدراج أو التحديث، ويشغّل Atlas Function لمزامنة البيانات أو إرسال إشعار. تتمرن على MongoDB Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ MongoDB Academy؟
لا تُشترط خبرة سابقة. MongoDB Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس MongoDB Academy هذا؟
نعم. كل درس في MongoDB Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- مشغلات قاعدة البيانات: الاستجابة لأحداث CRUD
- المشغلات المجدولة ومهام Cron
- كتابة Atlas Functions بلغة JavaScript
- نقاط نهاية HTTPS كخطافات ويب خفيفة