تخطَّ إلى المحتوى

🍃 شرح MongoDB

MongoDB Atlas والسحابة

الدرس 27 من 28· ⏱ 4 دقائق قراءة

MongoDB Atlas والسحابة

ما هو MongoDB Atlas؟

MongoDB Atlas هي خدمة قاعدة بيانات سحابية مُدارة بالكامل من MongoDB. توفر نشرًا آليًا، نسخًا احتياطيًا، مراقبة، وتوسيعًا أفقيًا بدون تدخل يدوي.

إعداد Cluster في Atlas

إنشاء حساب Atlas

  1. سجّل في https://cloud.mongodb.com
  2. اختر provider (AWS, GCP, Azure) والمنطقة الأقرب لك
  3. اختر طبقة الخدمة:
    • M0 (مجاني): 512 MB تخزين، مناسب للتجارب
    • M2/M5: خطط منخفضة التكلفة
    • M10+: إنتاج مع replication و backups

تكوين الشبكة (Network Security)

IP Whitelist

# إضافة IP حالي
curl -s ifconfig.me
# أضف IP في Atlas -> Network Access -> Add IP Address

# للسماح بالوصول من أي مكان (للتطوير فقط)
# 0.0.0.0/0

VPC Peering

لربط Atlas بشبكتك الافتراضية الخاصة:

  1. Network Access -> Peering -> Add Peering Connection
  2. اختر provider (AWS/GCP/Azure)
  3. أدخل معرف VPC وحساب الـ provider
  4. اقبل الطلب من الجانب الآخر

إنشاء مستخدم قاعدة بيانات

// عبر Atlas UI
// Database Access -> Add New Database User
// اختر user و password أو certificate

// الاتصال
mongosh "mongodb+srv://<cluster>.mongodb.net/<db>" \
  --username <user> \
  --password <pass>

Atlas Search مبني على Lucene ويوفر بحثًا نصيًا متقدمًا.

// Atlas UI: Search -> Create Index
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "string",
        "analyzer": "lucene.arabic"
      },
      "description": {
        "type": "string",
        "analyzer": "lucene.standard"
      },
      "price": { "type": "number" },
      "tags": { "type": "string", "multi": {
        "analyzer": "lucene.keyword"
      }},
      "createdAt": { "type": "date" }
    }
  }
}
db.products.aggregate([
  { $search: {
    index: "default",
    compound: {
      must: [
        { text: { query: "هاتف ذكي", path: "title", fuzzy: { maxEdits: 1 } }},
        { range: { path: "price", gte: 100, lte: 1000 }}
      ],
      should: [
        { text: { query: "جديد", path: "tags" }}
      ]
    }
  }},
  { $limit: 20 },
  { $project: { title: 1, price: 1, score: { $meta: "searchScore" }}}
])

Autocomplete

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": {
        "type": "autocomplete",
        "tokenizer": "lucene.edgengram",
        "minGrams": 2,
        "maxGrams": 15
      }
    }
  }
}
db.products.aggregate([
  { $search: {
    autocomplete: { query: "هات", path: "title" }
  }},
  { $limit: 5 },
  { $project: { title: 1 }}
])

Atlas Triggers

Triggers تستجيب للأحداث في قاعدة البيانات (CRUD) أو جداول زمنية.

// Database Trigger — مثال: إرسال بريد عند تقديم طلب
exports = async function(changeEvent) {
  const { fullDocument } = changeEvent;

  const emailService = context.services.get("email-service");
  await emailService.send({
    to: fullDocument.customerEmail,
    subject: "تم استلام طلبك",
    body: `رقم الطلب: ${fullDocument._id}`
  });
};

// Scheduled Trigger — كل ساعة
exports = async function() {
  const db = context.services.get("main").db("store");
  const expired = await db.collection("carts")
    .updateMany(
      { updatedAt: { $lt: new Date(Date.now() - 24*60*60*1000) }},
      { $set: { status: "abandoned" }}
    );
};

Serverless Instances

Atlas Serverless يتوسع تلقائيًا حسب الطلب، مناسب للتطبيقات ذات الحمولة المتغيرة.

# إنشاء serverless instance عبر Atlas CLI
atlas serverless create myServerless \
  --provider AWS \
  --region us-east-1

# أو عبر UI: Create -> Serverless

النسخ الاحتياطي والاستعادة

Backups التلقائية

# تفعيل النسخ الاحتياطي
atlas backups enable --clusterName myCluster

# استعادة نسخة
atlas backups restore \
  --clusterName myCluster \
  --snapshotId <snapshot_id>

Export البيانات

# Export باستخدام mongodump
mongodump --uri "mongodb+srv://<user>:<pass>@<cluster>.mongodb.net/<db>" \
  --out ./backup-$(date +%Y%m%d)

# Import باستخدام mongorestore
mongorestore --uri "mongodb+srv://<user>:<pass>@<cluster>.mongodb.net/<db>" \
  ./backup-20250101

Monitoring والتنبيهات

# عرض metrics
atlas metrics describe myCluster --period PT1H

# إنشاء تنبيه
atlas alerts create \
  --event "CPU_UTILIZATION_HIGH" \
  --metricThreshold 80 \
  --notificationType EMAIL \
  --notificationEmail "admin@example.com"

تمارين

  1. أنشئ Atlas cluster مجاني وتصل إليه من تطبيق Node.js
  2. أضف Search index مع autocomplete للغة العربية
  3. أنشئ Database trigger يُسجّل جميع عمليات الحذف في مجموعة logs
  4. جدول مهمة cron لإرسال تقرير يومي
شرح MongoDB Atlas والسحابة — MongoDB بالعربي
MongoDB Atlas والسحابةMongoDB بالعربي · The Code Fix

📚 لمزيد من التعمّق في MongoDB، راجِع التوثيق الرسمي لـ MongoDB.

هل كان هذا الدرس مفيدًا؟