NoSQL و MongoDB: فكر في Document مش Table
MongoDB document database؛ البيانات تتخزن في BSON documents داخل collections. BSON صيغة binary شبيهة بـ JSON لكنها تدعم أنواعًا إضافية مثل ObjectId و Date و Decimal128 و Binary. الـ document قد يحتوي nested objects و arrays. المرونة هنا معناها إن documents في collection ممكن تختلف في shape، وليس إن schema design غير مهم.
في relational database غالبًا تبدأ من entities والعلاقات ثم joins. في MongoDB ابدأ من query patterns: ما الذي يقرأ معًا؟ ما الذي يتغير معًا؟ ما حجم document المتوقع؟ هل العلاقة one-to-few أم one-to-many غير محدودة؟ هل تحتاج atomic update على مجموعة البيانات نفسها؟ شكل القراءة والكتابة هو اللي يوجه embedding/reference.
{
"_id": "...",
"customerId": "...",
"status": "Pending",
"createdAt": "2026-11-12T08:00:00Z",
"items": [
{ "productId": "...", "nameSnapshot": "Keyboard", "unitPrice": 1200, "quantity": 1 },
{ "productId": "...", "nameSnapshot": "Mouse", "unitPrice": 450, "quantity": 2 }
],
"total": 2100
}لاحظ وجود nameSnapshot و unitPrice داخل order item: دي لقطة تاريخية وقت الشراء، مش نسخة live من بيانات المنتج. لو اسم المنتج اتغير بعد الشراء، الفاتورة القديمة تظل تعكس ما تم شراؤه. ده مثال على أن duplication أحيانًا مقصودة لحماية business history.
Embedding vs Referencing: قرار Data Modeling
Embedding مناسب لما child data تُقرأ غالبًا مع parent، حجمها محدود، و ownership واضح. Reference مناسب لما البيانات كبيرة أو غير محدودة، تُقرأ بشكل مستقل، تُشارك بين parents، أو لها lifecycle منفصل. لا تعمل embedding لقائمة comments غير محدودة داخل post؛ document size له حد أقصى، والنمو المستمر يسبب hot document وتكلفة update.
| السؤال | Embedding يميل لأن يكون مناسبًا | Reference يميل لأن يكون مناسبًا |
|---|---|---|
| هل تُقرأ البيانات معًا؟ | غالبًا نعم | غالبًا لا |
| هل child bounded؟ | نعم، عدد محدود | لا، نمو غير محدود |
| هل child له lifecycle مستقل؟ | لا غالبًا | نعم |
| هل child مشترك بين parents؟ | نادرًا | نعم |
| هل تحتاج atomic update مع parent؟ | غالبًا أسهل داخل document | قد تحتاج transaction |
مفيش قاعدة «MongoDB لا تحتاج normalization». فيه توازن بين duplication و consistency. لو كررت بيانات customer في orders، قرر هل دي snapshot تاريخية أم denormalized cache تحتاج update propagation. وثّق المصدر الحقيقي لكل field.
MongoDB Data Modeling: Embed أم Reference؟
Embedding مناسب عندما child data تُقرأ غالبًا مع parent، وحجمها bounded، وتحتاج atomic update داخل document واحد. Referencing مناسب عندما العلاقة many-to-many أو child كبيرة/متغيرة أو لها lifecycle مستقل. لا تكرر نفس customer address في آلاف documents بلا update strategy؛ denormalization قرار consistency له تكلفة.
Atomicity الأساسية على document واحد؛ multi-document transactions متاحة في replica sets/sharded clusters لكنها أغلى وتحتاج حدودًا صغيرة. لا تستخدم transaction لإخفاء data model سيئ. صمم compound indexes وفق equality/sort/range، وراجع multikey indexes و index selectivity. Aggregation pipeline قد تستهلك memory؛ استخدم $match مبكرًا واستفد من indexable stages، وقس explain executionStats.
Document Modeling: Embed ولا Reference؟
MongoDB schema design يبدأ من access patterns. الـ embedding يقلل round trips ويتيح قراءة document واحدة بصورة ذرية، لكنه يكرر البيانات وقد يضخم document أو يسبب تحديثات واسعة. الـ referencing يقلل duplication ويدعم علاقات كثيرة إلى كثيرة، لكنه يتطلب queries إضافية أو aggregation lookup. لا تختار بناءً على أن MongoDB “NoSQL”؛ صمم حسب شكل القراءة والكتابة وحدود document.
MongoDB يضمن atomicity على مستوى document واحد. العمليات متعددة المستندات تحتاج transaction عند الحاجة، لكنها أكثر تكلفة وتتطلب replica set أو sharded cluster مناسب. أحيانًا تصميم aggregate بحيث تتغير بياناته معًا داخل document واحد أبسط وأسرع من transaction موزعة.
// Embed bounded recent events in the parent document:
db.customers.updateOne(
{ _id: customerId },
{ $push: {
recentEvents: {
$each: [{ type: "login", at: new Date() }],
$slice: -20
}
}
}
);
// Reference unbounded order history in a separate collection:
db.orders.createIndex({ customerId: 1, createdAt: -1 });الـ embedded array هنا bounded إلى آخر 20 حدثًا، فتجنب نمو document بلا حدود. لا تضع كل orders داخل customer document إذا كان العدد غير محدود أو كل order يتحدث مستقلًا. ضع indexes وفق query patterns، وتذكر أن كل index يزيد كلفة الكتابة.
CRUD و Filters و Projection و Update Operators
عمليات CRUD تستخدم filter documents لتحديد rows. لا تبعت empty filter بالغلط في update/delete؛ empty filter يطابق كل documents. Projection تحدد الحقول المرجعة لتقليل payload. Update operators مثل $set و $inc و $push تنفذ تحديثات ذرية على document.
var client = new MongoClient(connectionString);
var database = client.GetDatabase("shop");
var products = database.GetCollection<ProductDocument>("products");
var filter = Builders<ProductDocument>.Filter.And(
Builders<ProductDocument>.Filter.Eq(x => x.IsActive, true),
Builders<ProductDocument>.Filter.Gte(x => x.Price, 100m));
var projection = Builders<ProductDocument>.Projection
.Include(x => x.Id)
.Include(x => x.Name)
.Include(x => x.Price);
var result = await products.Find(filter)
.Project<ProductListItem>(projection)
.Limit(50)
.ToListAsync(ct);var filter = Builders<CartDocument>.Filter.And(
Builders<CartDocument>.Filter.Eq(x => x.Id, cartId),
Builders<CartDocument>.Filter.Eq(x => x.OwnerId, userId));
var update = Builders<CartDocument>.Update
.Inc(x => x.ItemsCount, 1)
.Set(x => x.UpdatedAt, DateTime.UtcNow);
var result = await carts.UpdateOneAsync(filter, update, cancellationToken: ct);
if (result.MatchedCount == 0)
throw new KeyNotFoundException("Cart not found.");ضمّن ownership/tenant predicate في filter عند الحاجة، مش بعد القراءة فقط. atomic update على document واحدة يمنع race conditions البسيطة مثل increment، لكنه لا يضمن business invariant عبر documents متعددة.
Array Updates: $push و$addToSet و$pull و Positional Operators
MongoDB arrays لها operators لتعديل elements داخل document. $push يضيف عنصرًا، $addToSet يضيف فقط لو غير موجود حسب equality semantics، $pull يحذف elements مطابقة، و positional operators مثل $/$[]/$[identifier] تستهدف array elements. لا ترسل document كاملًا من client وتعمل ReplaceOne لو تحتاج تعديل field واحد؛ ده قد يمسح fields أضافتها خدمة أخرى.
db.carts.updateOne(
{ _id: cartId, "items.productId": productId },
{ $inc: { "items.$.quantity": 1 }, $set: { updatedAt: new Date() } }
);الـ positional $ يعدل أول matching element حسب query. لو array فيها duplicate product IDs، حدد هل ده مسموح أم اجعل unique logic جزءًا من domain. اختبر concurrent updates على نفس document؛ single-document atomicity تحمي command، لكن business logic عبر عدة documents ما زالت تحتاج transaction/coordination.
BulkWrite و Write Concern
BulkWrite تجمع عدة write models في request واحدة وتقلل network round trips. Ordered bulk توقف عند أول error وفق semantics؛ unordered قد تستمر في باقي operations. لا تفترض all-or-nothing؛ bulk operations ليست transaction تلقائيًا. استخدم transaction لو atomicity عبر documents مطلوبة، أو صمم per-item result handling.
Write Concern يحدد acknowledgment/durability المطلوبة (مثل w:majority). أعلى durability قد تزيد latency. Read Concern يحدد consistency level للقراءة. Read Preference يحدد أي replica member يستقبل read؛ secondary reads قد تكون stale. اختَر الثلاثة وفق business semantics، ولا تجعل كل request تستخدم أقوى settings بلا حاجة.
Aggregation Pipeline
Aggregation pipeline سلسلة stages؛ كل stage تستقبل documents وتنتج documents للمرحلة التالية. من أشهرها $match للفلترة، $project لتشكيل الحقول، $group للتجميع، $sort للترتيب، $unwind لفرد arrays، $lookup لربط collections و $facet لتشغيل عدة sub-pipelines على نفس input.
db.orders.aggregate([
{ $match: { createdAt: { $gte: ISODate("2026-11-01") } } },
{ $group: {
_id: "$status",
count: { $sum: 1 },
revenue: { $sum: "$total" }
}},
{ $sort: { revenue: -1 } }
]);حاول دفع $match مبكرًا لتقليل documents الداخلة للمراحل التالية، واستخدم projection لتقليل fields عند الإمكان. لكن optimizer قد يعيد ترتيب بعض stages؛ افحص explain بدل الاعتماد على ترتيب شكلي فقط. $lookup ليس مجانيًا؛ كثرة joins قد تشير إلى model لا يناسب query patterns.
var pipeline = orders.Aggregate()
.Match(x => x.CreatedAt >= from)
.Group(x => x.Status, g => new
{
Status = g.Key,
Count = g.Count(),
Revenue = g.Sum(x => x.Total)
})
.SortByDescending(x => x.Revenue);
var summary = await pipeline.ToListAsync(ct);Indexes و Compound/Unique و explain()
MongoDB indexes تحسن reads بتكلفة storage و write overhead. Single-field index يخدم filter على field، compound index يخدم patterns متعددة مع أهمية ترتيب keys، unique index يفرض uniqueness، TTL index يحذف documents المنتهية تلقائيًا وفق field date، و text/geo indexes تخدم workloads خاصة.
db.orders.createIndex({ customerId: 1, createdAt: -1, _id: -1 });
db.users.createIndex({ normalizedEmail: 1 }, { unique: true });
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });Compound index يتبع ESR guideline غالبًا: Equality ثم Sort ثم Range، لكن ده heuristic وليس قانونًا. راجع prefix usage و selectivity وحجم index. TTL cleanup ليس بالضرورة لحظيًا عند لحظة expiry؛ لا تستخدمه كآلية authorization دقيقة أو deadline enforcement.
db.orders.find({ customerId: 42, status: "Pending" })
.sort({ createdAt: -1 })
.explain("executionStats");افحص winningPlan، totalKeysExamined، totalDocsExamined، nReturned، executionTimeMillis. نسبة docs examined إلى returned العالية قد تعني index غير مناسب أو filter غير selective. لا تضف index لكل query؛ كل index يزيد writes و memory pressure.
Consistency, Indexes and Aggregation Pipelines
MongoDB يتيح ضبط write concern و read concern و read preference. هذه الإعدادات تحدد متى يعتبر write acknowledged، وما مستوى البيانات الذي يمكن أن يراه القارئ، ومن أي member تتم القراءة. لا تخلط بين replication و backup: replica set يحسن availability، لكنه قد ينسخ حذفًا أو corruption منطقيًا أيضًا.
Aggregation pipeline تحول documents عبر مراحل مثل $match و $project و $group و $lookup. ادفع $match مبكرًا عندما يحافظ ذلك على semantics، واستفد من indexes في أول المراحل. استخدم explain("executionStats") لمراجعة docs examined مقابل returned.
db.orders.explain("executionStats").aggregate([
{ $match: { status: "paid", createdAt: { $gte: ISODate("2026-01-01") } } },
{ $group: { _id: "$customerId", revenue: { $sum: "$total" } } },
{ $sort: { revenue: -1 } },
{ $limit: 20 }
]);
// Compound index aligned with the initial filter:
db.orders.createIndex({ status: 1, createdAt: 1 });ترتيب compound index مهم بسبب prefix rule. راجع winning plan و keys/documents examined و execution time على بيانات ممثلة. لا ترفع read concern أو write concern لأعلى مستوى في كل العمليات بلا تقدير latency والتوافر المطلوبين.
Schema Validation و Serialization
Schema flexibility لا تعني قبول أي shape. MongoDB JSON Schema validation يقدر يفرض required fields و types و ranges. في C# Driver، attributes أو class maps تتحكم في BSON mapping، و [BsonId]/[BsonRepresentation] تغير serialization behavior. احذر اختلاف naming conventions أو nullable handling بين C# و existing documents.
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price", "isActive"],
properties: {
name: { bsonType: "string", minLength: 1 },
price: { bsonType: ["decimal", "double", "int", "long"], minimum: 0 },
isActive: { bsonType: "bool" }
}
}
},
validationLevel: "strict",
validationAction: "error"
});عند تغيير document schema، فكر في version field و migration strategy: هل ستعمل backfill؟ هل التطبيق يدعم الشكلين أثناء rollout؟ هل readers يتعاملون مع missing fields؟ لا تعتمد على تغيير C# class وحده كأنه migration تلقائي للبيانات القديمة.
Schema Versioning و Migrations في Document DB
لما تغير document shape، قد تكون عندك millions of old documents. استراتيجية lazy migration: reader يتعامل مع v1/v2 ويحدث document عند الكتابة؛ أو background migration batches؛ أو dual-read/dual-write خلال rollout. أضف schemaVersion لو التغيير جوهري، وحدد متى تتوقف عن دعم الشكل القديم.
لا تعمل migration واحدة ضخمة تقرأ كل collection في memory. استخدم cursor batches، checkpoints، rate limit، retries، و metrics. اختبر migration idempotency بحيث يمكن إعادة تشغيلها. schema validation قد تبدأ permissive ثم تصبح strict بعد backfill.
Atomicity و Transactions
MongoDB يضمن atomicity على مستوى document واحدة حتى لو التحديث لمس عدة fields داخلها. ده سبب مهم لتصميم aggregates داخل document. لو operation تمتد إلى عدة documents/collections، قد تحتاج multi-document transaction، لكن transactions لها تكلفة وتعقيد، ولا ينبغي استخدامها لتعويض model سيئ بلا تقييم.
لو business invariant تتطلب تحديث accountين، transaction قد تكون مناسبة. لو تقدر تصمم aggregate بحيث الحالة تتحدث atomically في document واحدة، قد يكون أبسط. لا تفترض أن multi-document transaction تجعل external HTTP call جزءًا من transaction؛ provider خارجي لا يتراجع تلقائيًا مع rollback.
using var session = await client.StartSessionAsync(cancellationToken: ct);
session.StartTransaction();
try
{
await accounts.UpdateOneAsync(session,
x => x.Id == fromId && x.Balance >= amount,
Builders<Account>.Update.Inc(x => x.Balance, -amount),
cancellationToken: ct);
await accounts.UpdateOneAsync(session,
x => x.Id == toId,
Builders<Account>.Update.Inc(x => x.Balance, amount),
cancellationToken: ct);
await session.CommitTransactionAsync(ct);
}
catch
{
await session.AbortTransactionAsync(CancellationToken.None);
throw;
}المثال يحتاج فحص matched counts و business validations قبل commit. استخدم retry semantics التي يوفرها driver للـ transient transaction errors بالشكل الموصى به، واجعل العملية idempotent. لا تكرر debit بعد unknown commit result من غير reconciliation.
Replication و Sharding: الصورة الكبيرة
Replica set مجموعة nodes تحتفظ بنسخ من نفس dataset: primary يستقبل writes و secondaries تكرر oplog. ده يوفر failover وقراءات ثانوية اختيارية، لكنه لا يعني zero data loss في كل write concern أو network partition. اقرأ write concern/read concern واختَر consistency المطلوبة. Secondary reads قد تكون stale.
Sharding يقسم البيانات عبر shards لزيادة capacity/throughput. اختيار shard key قرار معماري صعب: لازم يوزع writes وال storage جيدًا، ويدعم query patterns، ويتجنب hotspots. shard key سيئ قد يسبب scatter-gather أو hotspot. لا تبدأ sharding لمجرد كبر اسمها؛ ابدأ بقياس replica set limits و query patterns والتشغيل.
Change Streams تسمح بمراقبة تغييرات collections/DB/deployment، ومفيدة للتكامل event-driven. لكنها ليست بديلًا تلقائيًا عن transactional outbox في كل تصميم؛ افهم resume tokens، retention/oplog window، duplicate delivery، checkpointing، وإعادة الاتصال.
Change Streams: Resume Tokens و At-Least-Once
Change Streams تسمح بمراقبة changes على collection/database/deployment في replica set أو sharded cluster. كل event تحمل resume token يمكن استخدامه لاستكمال stream بعد reconnect ضمن حدود oplog retention. consumer يجب يحفظ checkpoint بعد معالجة event، ويتعامل مع duplicate/replay، ويفصل processing time عن cursor lifetime.
لو consumer يعالج event ثم crash قبل حفظ checkpoint، قد يستقبلها مرة أخرى؛ handler لازم idempotent. لو checkpoint تحفظ قبل side effect، قد تضيع side effect. استخدم inbox/deduplication record أو transaction semantics مناسبة. Change Stream ليست message broker عامة؛ راجع retention, backpressure, filtering, schema changes و permissions.
Replica Set Read/Write Semantics
Primary election/failover قد ينتج transient errors. Driver يملك retryable reads/writes لبعض operations وفق settings، لكن application ما زالت تحتاج idempotency عند ambiguous outcome. WriteConcern w:majority يقلل احتمال فقد acknowledged writes في failover، لكنه لا يعني distributed transaction مع systems أخرى.
ReadPreference secondaryPreferred قد يخفف primary load لكنه يسمح stale reads. لا تستخدم secondary read لاتخاذ قرار financial/authorization حساس إذا consistency المطلوبة غير مضمونة. اقرأ عن causal consistency/session semantics لو تحتاج read-your-writes عبر replica set.
C# Driver: DI و Error Handling
في ASP.NET Core، غالبًا تسجل MongoClient كـ Singleton لأنه thread-safe ويحتوي connection pools؛ لا تنشئ client جديدًا لكل request. الـ database/collection handles lightweight. استخدم typed collections و CancellationToken، وخلي repository abstraction تعبر عن use-case queries بدل generic repository يسرّب تفاصيل Mongo لكل الطبقات.
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5);
settings.ConnectTimeout = TimeSpan.FromSeconds(5);
builder.Services.AddSingleton<IMongoClient>(_ => new MongoClient(settings));
builder.Services.AddSingleton(sp =>
sp.GetRequiredService<IMongoClient>().GetDatabase("shop"));تعامل مع duplicate key (مثل code 11000) كـ conflict business عند اللزوم، ومع transient network errors عبر retry محدود مع jitter. لا تعِد محاولة كل exception؛ validation/schema errors و unauthorized errors غالبًا permanent. راقب pool usage، server selection failures، slow query logs و replication lag.
MongoDB Security و Operations Checklist
- فعّل authentication و TLS، وامنح application user أقل privileges.
- افصل users لكل app/environment، ولا تستخدم admin account داخل API.
- راجع network exposure و IP allow-lists/private networking.
- شفر backups واحمِ connection strings/secrets.
- راقب replication lag، elections، connection pool، slow queries، index size و disk.
- اختبر backup restore، وليس وجود backup فقط.
- راجع explain على query patterns المهمة، وراقب COLLSCAN غير المقصود.
- استخدم tenant filter في كل retrieval/vector query.
Backup/restore strategy يجب تحدد RPO/RTO. mongodump/restore مناسبة لبعض الحالات، و cloud managed backups/PITR قد تكون أفضل حسب deployment. اختبر restore إلى بيئة منفصلة وتحقق من indexes/users/validators/collections.
MongoDB أم SQL Server؟ و Vector Search Awareness
SQL Server مناسب عندما العلاقات وال joins وال constraints والمعاملات relational مركزية. MongoDB مناسب عندما document aggregate يطابق read/write patterns والـ schema evolution مفيد. الاتنين يقدمان transactions و indexes؛ الفرق في modeling trade-offs والـ ecosystem، مش «SQL قديم و NoSQL حديث». لا تستخدم MongoDB لأن البيانات JSON فقط؛ relational databases تدعم JSON أيضًا.
Atlas Vector Search يضيف vector retrieval إلى MongoDB ecosystem. اختبر filtering و tenant isolation و recall/latency و index build/update costs. لا تخلط النصوص والـ embeddings من نماذج مختلفة في نفس vector field من غير versioning/dimension controls. تأكد أن authorization filter جزء من retrieval pipeline.
اختبر فهمك
متى تختار embedding؟
هل document database تعني schema-free؟
هل TTL index يحذف document في الثانية المحددة تمامًا؟
ما الذي يضمنه MongoDB atomicity افتراضيًا؟
لماذا MongoClient غالبًا Singleton؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
خريطة التغطية: 24 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.