Skip to content

MongoDB with Go: CRUD, Filters, Generics Helpers, Relationships ​

"The MongoDB supported driver for Go." — README مخزن mongo-go-driver، v2.8.2

خلاصه (Summary): درایور رسمی (Driver) mongo-go-driver v2 با مسیر go.mongodb.org/mongo-driver/v2، structهای Go را به سندهای BSON و برعکس تبدیل می‌کند؛ CRUD، فیلتر، به‌روزرسانی، نمایه، تجمیع، تراکنش و جریان تغییرات را اجرا می‌کند و برای هر فراخوانی شبکه یک context.Context می‌گیرد. در این فصل روی آن یک لایهٔ دادهٔ کوچک و قابل تست با Repository[T] جنریک می‌سازیم. تمرکز (Focus): اتصال با mongo.Connect، options.Client و .ApplyURI و مدیریت عمر آن با Ping/Disconnect؛ تنظیم pool و timeout؛ انتخاب bson.D در برابر bson.M و نگاشت با tagهای _id، omitempty و inline؛ درج با InsertOne/InsertMany و خواندن با FindOne یا Find و cursor با Next، Decode، All و Close؛ ساخت فیلتر، projection و sort؛ مقایسهٔ limit/skip با صفحه‌بندی بازه‌ای روی _id؛ تغییر با UpdateOne/UpdateMany و $set/$inc/$push/$addToSet، upsert، ReplaceOne، DeleteOne، FindOneAndUpdate و نوشتن دسته‌ای؛ نمایه‌های unique، compound، TTL و text، pipeline تجمیع، فیلتر تایپ‌دار و Repository[T]، تعبیه در برابر ارجاع و $lookup؛ تراکنش با WithTransaction، read/write concern، جریان تغییرات، مدیریت mongo.ErrNoDocuments و duplicate key 11000، اعتبارسنجی $jsonSchema و تست بدون سرور. هدف یادگیری (Learning goal): یک client برای تمام عمر پردازه باز کنید، سندها را با tagهایی که معنایشان را می‌دانید به struct نگاشت کنید، query را به‌صورت bson.D مرتب و تایپ‌دار بسازید و با بازهٔ _id صفحه‌بندی کنید. داده‌ای را که با هم خوانده می‌شود در یک سند و بقیه را در collection جدا بگذارید؛ نوشتن چندسندی را فقط با replica set در WithTransaction قرار دهید؛ خطاهای driver را به خطاهای دامنه تبدیل کنید و کل لایه را پشت interface و fake تست کنید.

این صفحه مسئول driver در Go است: اتصال، نگاشت، query، update، index، aggregation و تست از Go. خود MongoDB، یعنی مدل سند، replica set، sharding و WiredTiger، در MongoDB در عمق است؛ نقشهٔ پایگاه‌های document، key-value، wide-column و graph در خانواده‌ها و مدل‌های دادهٔ NoSQL، و شکل دادن به جدول و سند در طراحی Schema، نرمال‌سازی و نوع داده. در سمت Go، نحو generics در Generics، tagهای struct و JSON در JSON، XML و Struct Tags، لغو و مهلت در context، معادل SQL این فصل در database/sql و pgx، و محل اتصال repository به handlerهای HTTP در ساخت REST API در Go است. خلاصهٔ دستورهای shell را در یادسپار MongoDB می‌بینید.

حقایق این صفحه با سورس و README نسخهٔ v2.8.2 در GitHub، راهنمای مهاجرت از 1.x به 2.0، مستند driver در mongodb.com، راهنمای MongoDB Server دربارهٔ مدل‌سازی، تراکنش، index، aggregation، $jsonSchema، change stream، GridFS و کدهای خطا، صفحهٔ MongoDB در Laravel 13، مستند بستهٔ Laravel MongoDB و یادداشت‌های انتشار Go 1.18 و 1.24 بررسی شده‌اند. pkg.go.dev به دریافت اسکریپتی پاسخ 403 می‌دهد؛ بنابراین جزئیات API از سورس tagشده آمده‌اند. نمونه‌ها go 1.24 اعلام می‌کنند و driver را روی v2.8.2 ثابت کرده‌اند؛ آخرین نسخه‌ای که go.mod آن هنوز go 1.19 است. نسخهٔ v2.9.0 و بعد از آن go 1.25.0 اعلام می‌کنند. نمونه‌ها روی Go 1.27.4 در macOS کامپایل، vet و با -race تست شده‌اند. روی ماشین آماده‌سازی MongoDB در دسترس نبود: تست‌ها از سازنده‌های خود driver، یعنی mongo.NewCursorFromDocuments و mongo.NewSingleResultFromDocument، و fake استفاده می‌کنند؛ هر مرحلهٔ آزمایشگاه که سرور لازم دارد با «انتظار می‌رود؛ اجرا نشده» مشخص شده است.

نقشهٔ صفحه (Page map) ​

اگر دنبال این هستیدبروید به
جدول‌هایی که در یک دقیقه حفظ می‌شوندهمه‌چیز در یک دقیقه
چرا سرویس Go دور driver یک لایهٔ داده لازم داردچرا وجود دارد
انتخاب driver و نسخه و تغییرهای v2از کجا آمده
قبل و بعد یک لایهٔ queryGo
اتصال با mongo.Connect، ApplyURI، Ping، Disconnect و تنظیم pool و timeoutاتصال
تفاوت bson.D، bson.M، bson.A و bson.Eنوع‌های BSON
tagهای struct، _id، ObjectID، omitempty، inline و زماننگاشت struct
درج با InsertOne و InsertManyدرج
خواندن با FindOne و معنای ErrNoDocumentsFindOne
Find و کار با cursor از طریق Next، Decode، All و CloseFind و cursor
فیلتر با $eq، $gt، $in، $regex و $elemMatchفیلترها
انتخاب فیلدها و ترتیب نتیجه با projection و sortProjection و sort
مقایسهٔ limit/skip با بازهٔ _id برای صفحه‌بندیصفحه‌بندی
تغییر با UpdateOne، UpdateMany، $set، $inc، $push و $addToSetبه‌روزرسانی
کاربرد upsert، ReplaceOne و FindOneAndUpdateUpsert و جایگزینی
حذف با DeleteOne و DeleteManyحذف
نوشتن دسته‌ای عملیات متفاوتBulk write
نمایه‌های unique، compound، TTL و textنمایه‌ها
تجمیع با $match، $group، $lookup، $unwind و $projectتجمیع
فیلترهایی که کامپایلر نوعشان را بررسی می‌کندفیلتر تایپ‌دار
ساخت Repository[T]Repository جنریک
تعبیه در برابر ارجاع، $lookup و denormalizationرابطه‌ها
session، WithTransaction و الزام replica setتراکنش‌ها
تضمین‌های read concern و write concernConcern خواندن و نوشتن
جریان تغییرات و نگهداری فایل با GridFSChange stream و GridFS
duplicate key 11000، IsDuplicateKeyError و timeoutمدیریت خطا
اعتبارسنجی با $jsonSchemaاعتبارسنجی Schema
تست با fake و testcontainersتست
باگ‌های رایج و راه‌حلشانحل مسئله‌های کلاسیک
چه وقت از چه استفاده کنیمانتخاب
از monolith تا سیستم توزیع‌شدهدر معماری
اجرای تست‌ها روی ماشین خودتانآزمایشگاه
Eloquent و بستهٔ Laravel MongoDBبرای توسعه‌دهندگان PHP/Laravel

همه‌چیز در یک دقیقه (One minute) ​

مسیر نوشتن و خواندن. هر فراخوانی متدی روی *mongo.Collection است، ابتدا ctx می‌گیرد و یک struct نتیجه یا مکان‌نما (Cursor) برمی‌گرداند. هر سطر در فهرست مفاهیم باز می‌شود.

هدفمتدخروجیوقتی چیزی تطبیق نداردکاربرد معمول
افزودن یک سندInsertOne*InsertOneResult با InsertedIDموضوعیت نداردساخت کاربر
افزودن چند سندInsertMany*InsertManyResultموضوعیت نداردورود یک دسته داده
خواندن یکیFindOne(...).Decode(&v)*SingleResultخطای mongo.ErrNoDocumentsبارگذاری با id یا email
خواندن چندتاFind سپس Next/Decode یا All*Cursorcursor خالی، بدون خطافهرست و خروجی گرفتن
تغییر یکیUpdateOne*UpdateResultMatchedCount == 0، بدون خطا$set، $inc
تغییر چندتاUpdateMany*UpdateResultMatchedCount == 0، بدون خطاتغییر دسته‌ای وضعیت
جایگزینی کل سندReplaceOne*UpdateResultMatchedCount == 0، بدون خطاذخیرهٔ کامل
تغییر و خواندن نتیجهFindOneAndUpdate*SingleResultخطای ErrNoDocumentsشمارنده و صف
حذفDeleteOne، DeleteMany*DeleteResultDeletedCount == 0، بدون خطاحذف با id
چند نوشتن، یک درخواست برای هر دستهٔ حداکثر 100,000تاییBulkWrite*BulkWriteResultشمارش به‌ازای هر مدلکارهای همگام‌سازی
شمارشCountDocumentsint640شمارش دقیق
گزارشAggregate*Cursorcursor خالیگروه‌بندی، join و تغییر شکل

اجزای BSON. driver چهار نوع برای ساخت دادهٔ BSON نام می‌برد: D سند مرتب، M map نامرتب، A آرایه، و E یک عضو D.

نوعترتیب حفظ می‌شود؟کاربردهرگز برای این استفاده نکنید
bson.Dبله، slice از bson.Eفیلتر چندکلیدی، sort، کلید index، فرمان و مرحلهٔ pipelineمحدودیتی ندارد؛ پیش‌فرض امن است
bson.Mنه، map در Go استخواندن سندی که شکلش را نمی‌دانیدسند sort، کلید index و کلید اول فرمان
bson.Aبلهآرایه در فیلتر و update، مانند $and و $in—
bson.Eموضوعیت نداردیک جفت Key/Value—
bson.Rawبله، به‌شکل بایتخواندن بدون کپی و payload رویداد تغییرساخت query

خطاهایی که مدیریت می‌کنید.

متن یا مقدارمحل ایجادمعناتلاش مجدد (Retry)؟
mongo: no documents in result (mongo.ErrNoDocuments)FindOne، FindOneAndUpdate، FindOneAndDeleteچیزی مطابق نبودنه؛ به «پیدا نشد» تبدیل کنید
E11000 duplicate key error، کد 11000، DuplicateKeyInsertOne، UpdateOne با upsert، InsertManyنقض نمایهٔ یکتانه؛ به «تعارض» تبدیل کنید
server selection error: context deadline exceededهر فراخوانی، Pingدر مهلت انتخاب سرور، سرور مناسب پیدا نشدشاید، با backoff
context deadline exceeded (mongo.IsTimeout)هر فراخوانی دارای ctx یا Timeout روی clientبودجه تمام شدفقط اگر هنوز بودجه مانده
برچسب TransientTransactionErrorداخل تراکنشاجرای دوبارهٔ کل تراکنش ممکن استبله؛ WithTransaction انجام می‌دهد
خطای سرور هنگام شروع تراکنش؛ متن بین نسخه‌ها فرق داردتراکنش روی سرور standalonereplica set ندارید؛ standalone تراکنش نداردنه؛ استقرار را اصلاح کنید

چرا وجود دارد (Why) ​

driver ابزارهای پایه را می‌دهد: handle یک مجموعه (Collection)، مقدارهای bson و cursor. سرویس واقعی بیشتر از این لازم دارد. باید یک جا نام collection و شکل سند را بشناسد، یک جا خطای driver را به زبان بقیهٔ برنامه برگرداند، یک جا فیلتر را از مقدار تایپ‌دار بسازد نه JSON درخواست، و مرزی داشته باشد که تست بتواند پایگاه داده را عوض کند. بدون این مرز، هر handler یک *mongo.Collection نگه می‌دارد، از map[string]any یک bson.M می‌سازد، بستن cursor را فراموش می‌کند و فقط با سرور روشن تست می‌شود.

فراخوانی مستقیم driver در handlerیک لایهٔ دادهٔ کوچک
ساخت فیلتر از map درخواستساخت فیلتر از مقدار تایپ‌دار
نشت mongo.ErrNoDocuments به کد HTTPتنها معنای نبودن برای صدازننده ErrNotFound است
هر تست به mongod نیاز داردبیشتر تست‌ها fake پشت interface دارند
نام collection و فیلد به‌شکل string در همه‌جایک‌بار در ثابت‌ها و فیلدهای تایپ‌دار تعریف می‌شوند
کد کمتر در شروعچند صد خط که یک‌بار نوشته و بارها استفاده می‌شود

تصویری از زندگی روزمره. کمد پروندهٔ یک درمانگاه را تصور کنید. کشو همان collection و پوشه همان سند است. پوشه می‌تواند برگه‌های مرتبط را داخل خودش نگه دارد، یعنی دادهٔ تعبیه‌شده، یا یادداشتی داشته باشد که «پروندهٔ 4711 را ببینید»، یعنی ارجاع. مسئول پذیرش، همان repository، تنها کسی است که کشو را باز می‌کند: قواعد برچسب‌گذاری را می‌داند، به‌جای دست خالی برگشتن به پزشک می‌گوید «چنین بیماری نداریم» و دو پوشه با یک شماره ثبت نمی‌کند. اگر نباشد، همکارش با یک کشوی مقوایی، یعنی fake، می‌تواند کل روال را تمرین کند.

سه بدفهمی رایج، از همان اول ​

  1. «MongoDB schema ندارد، پس struct را هرطور خواستم عوض می‌کنم.» سرور تا از او نخواهید شکلی را تحمیل نمی‌کند؛ ولی struct در Go خودش schema کد است. تغییر نام یک فیلد بی‌سروصدا خواندن سندهای قدیمی را متوقف می‌کند. tag، نسخه‌بندی سند و $jsonSchema ابزار کنترل‌اند؛ نگاشت struct و اعتبارسنجی Schema را ببینید.
  2. «mongo.Connect وصل می‌شود.» client را می‌سازد و monitorهای پس‌زمینه را راه می‌اندازد، اما پاسخ دادن سرور را ثابت نمی‌کند. host اشتباه تازه در اولین query به خطای انتخاب سرور می‌رسد؛ در شروع Ping بزنید؛ اتصال.
  3. «تراکنش همه‌چیز را امن می‌کند؛ همه‌جا تراکنش می‌گذارم.» نوشتن یک سند از قبل اتمیک است. تراکنش replica set یا sharded cluster می‌خواهد، تأخیر اضافه می‌کند و شاید callback را دوباره اجرا کند. داده را طوری مدل کنید که بیشتر نوشتن‌ها یک سند را لمس کنند؛ تراکنش‌ها.

از کجا آمده (History) ​

MongoDB, Inc. driver رسمی Go را در مخزن mongodb/mongo-go-driver نگهداری می‌کند. نسخهٔ 1.x در go.mongodb.org/mongo-driver بود. شاخهٔ 2.0 به مسیر major تازهٔ go.mongodb.org/mongo-driver/v2 رفت؛ راهنمای مهاجرت برای بازنویسی importها ابزار mod upgrade --mod-name=go.mongodb.org/mongo-driver را پیشنهاد می‌کند. هنگام خواندن آموزش قدیمی، این تغییرها مهم‌اند:

عادت v1 در بسیاری از نوشته‌هاv2 در این فصل
mongo.Connect(ctx, options.Client()...)mongo.Connect(options.Client()...)؛ پارامتر context حذف شد، چون اتصال‌دهندهٔ استقرار «doesn’t accept a context»
client.Connect(ctx)حذف شده؛ mongo.Connect client متصل برمی‌گرداند
primitive.ObjectID از bson/primitivebson.ObjectID؛ بستهٔ bson/primitive در bson ادغام شد
آرگومان callback از نوع mongo.SessionContextیک context.Context معمولی که session را حمل می‌کند
SingleResult.DecodeBytesSingleResult.Raw
پر کردن مستقیم struct گزینه‌هاbuilder گزینه‌ها sliceای از تابع‌های setter نگه می‌دارد؛ options.Find().SetLimit(...) همان‌طور کار می‌کند
Cursor.SetMaxTimeCursor.SetMaxAwaitTime

README نسخهٔ v2 برای شاخهٔ 2.8.x شرط «Go 1.19 or higher» و «MongoDB 4.2 and higher» را بیان می‌کند. انتشارهای بعدی 2.x حداقل Go را به 1.25 بردند؛ go.mod در v2.9.0 مقدار go 1.25.0 دارد. برای همین نمونه‌های این فصل v2.8.2 را ثابت کرده‌اند و در go.mod خودشان go 1.24 نگه داشته‌اند. اگر پروژهٔ تازه‌ای روی Go 1.25 یا جدیدتر آغاز می‌کنید، آخرین v2 را بگیرید.

نوع‌های جنریک (Generics) با Go 1.18 آمدند؛ یادداشت انتشار تغییرهای زبان را «fully backward-compatible» می‌نامد. لایهٔ دادهٔ این فصل دقیقاً برای یک کار از آن‌ها استفاده می‌کند: نوشتن یک repository که برای هر نوع سند به کار برود.

Go ​

قبل (Before) ​

شکل رایج اولین کد MongoDB این است: فیلتر ورود از بدنهٔ درخواست داخل bson.M کپی می‌شود، تابع پاسخ‌دهنده به درخواست context.Background() می‌سازد، cursor هرگز بسته نمی‌شود و صفحه‌بندی با skip انجام می‌شود. کد کامپایل و اجرا می‌شود و در روز خلوت جواب می‌دهد. sort آن از همین حالا bson.D است؛ driver یک bson.M چندکلیدی را برای sort نمی‌پذیرد؛ نوع‌های BSON. تست مشکل را نشان می‌دهد: بدنهٔ {"email":"a@example.test","password":{"$ne":""}} شرط رمز عبور را به operator تبدیل می‌کند. فیلتر فرستاده‌شده نیز {"email":"a@example.test","password":{"$ne":""}} است و حساب‌های دارای رمز عبور را تطبیق می‌دهد.

go
// Package before is the shape most first MongoDB code takes: untyped filters
// built from request data, context.Background everywhere, no Close, and a
// skip-based page. It compiles and runs, and it is still the wrong design.
package before

import (
	"context"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// LoginFilter copies whatever the client sent into the query. With the body
// {"email":"a@example.test","password":{"$ne":""}} the password clause becomes
// an operator and matches every account that has a password.
func LoginFilter(body map[string]any) bson.M {
	return bson.M{"email": body["email"], "password": body["password"]}
}

// UserSort is the sort FindUsers sends. The driver rejects a bson.M with more
// than one key as a sort (ErrMapForOrderedArgument), so even the "before" code
// has to use an ordered bson.D here.
func UserSort() any {
	return bson.D{{Key: "age", Value: -1}, {Key: "name", Value: 1}}
}

// FindUsers still has design smells: context.Background ignores the request's
// lifetime, the cursor is never closed, and skip pagination gets slower with
// every page. It does check its errors, so it runs.
func FindUsers(coll *mongo.Collection, page int64) ([]bson.M, error) {
	cur, err := coll.Find(context.Background(), bson.M{},
		options.Find().SetSort(UserSort()).SetSkip(page*20).SetLimit(20))
	if err != nil {
		return nil, err
	}
	var out []bson.M
	for cur.Next(context.Background()) {
		var doc bson.M
		if err := cur.Decode(&doc); err != nil {
			return nil, err
		}
		out = append(out, doc)
	}
	return out, cur.Err()
}
go
package before

import (
	"encoding/json"
	"testing"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func TestOperatorInjectionPassesThrough(t *testing.T) {
	var body map[string]any
	if err := json.Unmarshal([]byte(`{"email":"a@example.test","password":{"$ne":""}}`), &body); err != nil {
		t.Fatal(err)
	}
	raw, err := bson.Marshal(LoginFilter(body))
	if err != nil {
		t.Fatal(err)
	}
	v, err := bson.Raw(raw).LookupErr("password", "$ne")
	if err != nil {
		t.Fatalf("the injected $ne operator should survive in the filter: %v", err)
	}
	if v.StringValue() != "" {
		t.Fatalf("unexpected operand %v", v)
	}
	ej, _ := bson.MarshalExtJSON(LoginFilter(body), false, false)
	t.Logf("filter sent to the server: %s", ej)
}

// The sort used by FindUsers must be an ordered document. The driver rejects a
// bson.M with more than one key as a sort (ErrMapForOrderedArgument), so
// before-code that runs has to use bson.D.
func TestSortIsOrdered(t *testing.T) {
	d, ok := UserSort().(bson.D)
	if !ok {
		t.Fatalf("UserSort must be a bson.D, got %T", UserSort())
	}
	b, err := bson.MarshalExtJSON(d, false, false)
	if err != nil || string(b) != `{"age":-1,"name":1}` {
		t.Fatalf("sort = %s err=%v", b, err)
	}
}

بعد (After) ​

همان دو تابع با ورودی تایپ‌دار، context صدازننده، cursor بسته‌شده، بررسی خطا، sort مرتب و صفحه‌بندی بازه‌ای نوشته شده‌اند. رمز عبور هرگز وارد query نمی‌شود: Authenticate کاربر را با email از interface به نام Users بارگذاری می‌کند؛ Store متکی به MongoDB دور Repository[User] قرار دارد. سپس hash ذخیره‌شدهٔ bcrypt را در Go مقایسه می‌کند. email ناشناخته و رمز اشتباه هر دو ErrBadCredentials می‌دهند؛ برای انتخاب hash، احراز هویت در Go را ببینید. تست‌ها با Users جعلی ثابت می‌کنند حالت درست، اشتباه، ناشناخته و خرابی زیرساخت همان رفتار تعریف‌شده را دارند و query فقط email دارد. همچنین ثابت می‌کنند object در فیلد password از JSON اصلاً داخل فیلد string decode نمی‌شود.

go
// Package after fixes the same two functions: typed inputs that cannot become
// operators, the caller's context, closed cursors, checked errors and ordered
// sort keys.
package after

import (
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"golang.org/x/crypto/bcrypt"

	"academy/mongodb-with-go/filters"
	"academy/mongodb-with-go/models"
	"academy/mongodb-with-go/repo"
)

// LoginFilter takes a string, so a JSON object in the request fails to decode
// before it gets here. Only the email is in the query.
func LoginFilter(email string) bson.D {
	return filters.ByEmail(email)
}

// ErrBadCredentials is returned for an unknown email and for a wrong password
// alike, so the caller cannot tell which accounts exist.
var ErrBadCredentials = errors.New("after: bad credentials")

// Users loads a user by email. Store is the MongoDB implementation.
type Users interface {
	FindByEmail(ctx context.Context, email string) (*models.User, error)
}

// Store implements Users on top of the generic repository.
type Store struct{ R *repo.Repository[models.User] }

// FindByEmail runs the typed email filter.
func (s Store) FindByEmail(ctx context.Context, email string) (*models.User, error) {
	return s.R.Get(ctx, LoginFilter(email))
}

// HashPassword returns a bcrypt hash. Real systems follow the choices in the
// authentication chapter (Argon2id or bcrypt with a tuned cost).
func HashPassword(password string) string {
	h, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		panic(err) // only for a password longer than 72 bytes
	}
	return string(h)
}

// Authenticate loads the user by email and compares the stored hash in Go. The
// password never appears in a query, so no operator can be smuggled into it.
func Authenticate(ctx context.Context, users Users, email, password string) (*models.User, error) {
	u, err := users.FindByEmail(ctx, email)
	if errors.Is(err, repo.ErrNotFound) {
		return nil, ErrBadCredentials
	}
	if err != nil {
		return nil, err
	}
	if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil {
		return nil, ErrBadCredentials
	}
	return u, nil
}

// FindUsers streams one page of users with range pagination on _id.
func FindUsers(ctx context.Context, coll *mongo.Collection, last bson.ObjectID) ([]models.User, error) {
	filter, opts := filters.After(last, 20)
	cur, err := coll.Find(ctx, filter, opts.SetSort(filters.Sort(filters.Key{Field: "_id"})))
	if err != nil {
		return nil, err
	}
	defer cur.Close(ctx)

	var out []models.User
	if err := cur.All(ctx, &out); err != nil {
		return nil, err
	}
	return out, nil
}

// SortOptions shows the ordered form of the sort that before.FindUsers got wrong.
func SortOptions() *options.FindOptionsBuilder {
	return options.Find().SetSort(filters.Sort(
		filters.Key{Field: "age", Desc: true},
		filters.Key{Field: "name"},
	))
}
go
package after

import (
	"context"
	"encoding/json"
	"errors"
	"testing"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"

	"academy/mongodb-with-go/filters"
	"academy/mongodb-with-go/models"
	"academy/mongodb-with-go/repo"
)

func TestObjectInPasswordFieldDoesNotDecodeIntoString(t *testing.T) {
	var req struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	err := json.Unmarshal([]byte(`{"email":"a@example.test","password":{"$ne":""}}`), &req)
	if err == nil {
		t.Fatal("an object must not decode into a string field")
	}
}

func TestEmailStaysAValueEvenIfItLooksLikeAnOperator(t *testing.T) {
	b, err := bson.MarshalExtJSON(LoginFilter(`{"$ne":""}`), false, false)
	if err != nil {
		t.Fatal(err)
	}
	if string(b) != `{"email":"{\"$ne\":\"\"}"}` {
		t.Fatalf("got %s", b)
	}
}

func TestSortKeepsOrder(t *testing.T) {
	o := &options.FindOptions{}
	for _, set := range SortOptions().List() {
		if err := set(o); err != nil {
			t.Fatal(err)
		}
	}
	b, _ := bson.MarshalExtJSON(o.Sort, false, false)
	if string(b) != `{"age":-1,"name":1}` {
		t.Fatalf("got %s", b)
	}
}

type fakeUsers struct {
	u   *models.User
	err error
	got bson.D
}

func (f *fakeUsers) FindByEmail(_ context.Context, email string) (*models.User, error) {
	f.got = filters.ByEmail(email)
	return f.u, f.err
}

func TestAuthenticate(t *testing.T) {
	hash := HashPassword("correct horse")
	u := &models.User{Email: "a@example.test", PasswordHash: hash}
	ctx := context.Background()

	if got, err := Authenticate(ctx, &fakeUsers{u: u}, "a@example.test", "correct horse"); err != nil || got.Email != "a@example.test" {
		t.Fatalf("valid login: %v %v", got, err)
	}
	if _, err := Authenticate(ctx, &fakeUsers{u: u}, "a@example.test", "wrong"); !errors.Is(err, ErrBadCredentials) {
		t.Fatalf("wrong password: %v", err)
	}
	if _, err := Authenticate(ctx, &fakeUsers{err: repo.ErrNotFound}, "x@example.test", "whatever"); !errors.Is(err, ErrBadCredentials) {
		t.Fatalf("unknown user must look like a wrong password, got %v", err)
	}
	boom := errors.New("db down")
	if _, err := Authenticate(ctx, &fakeUsers{err: boom}, "a@example.test", "x"); !errors.Is(err, boom) {
		t.Fatalf("infrastructure errors pass through, got %v", err)
	}
}

func TestPasswordIsNeverInTheQuery(t *testing.T) {
	f := &fakeUsers{u: &models.User{PasswordHash: HashPassword("p")}}
	_, _ = Authenticate(context.Background(), f, "a@example.test", "p")
	b, _ := bson.MarshalExtJSON(f.got, false, false)
	if string(b) != `{"email":"a@example.test"}` {
		t.Fatalf("query = %s", b)
	}
}

زاویهٔ Go ​

مزیت Go در سه نقطه دیده می‌شود. نوع‌های ایستا: bson.D و wrapper تایپ‌دار فیلد اجازه نمی‌دهند جای operator از ورودی کاربر پر شود. Interface: repository فقط شش متدی را می‌خواهد که استفاده می‌کند و *mongo.Collection بدون adapter آن‌ها را دارد؛ بنابراین fake حدود دوازده خط می‌شود. Context: هر فراخوانی شبکه ctx می‌گیرد؛ بستن تب مرورگر، رسیدن مهلت یا خاموشی تا فراخوانی دیتابیس می‌رسد؛ context. هزینه، پرحرفی کد است: bson.D{{Key: "a", Value: 1}} از literal جاوااسکریپت بلندتر است. کامپایلر هم نام فیلد داخل string را بررسی نمی‌کند؛ فیلتر تایپ‌دار این فصل همین مشکل را کمتر می‌کند.

فهرست مفاهیم ​

اتصال: Connect، ApplyURI، Ping، Disconnect و گزینه‌های pool حیاتی ​

به زبان ساده: برای هر پردازه یک *mongo.Client. این client مالک مخزن اتصال (Connection pool) به هر سرور استقرار و چند goroutine پس‌زمینه برای پایش سرورهاست. یک‌بار در main ساخته می‌شود، به لایه‌های پایین داده می‌شود و هنگام توقف پردازه اتصال‌هایش بسته می‌شوند.

بدفهمی رایج: «اگر سرور خاموش باشد mongo.Connect خطا می‌دهد.» فقط گزینهٔ نامعتبر خطا می‌دهد. مستند driver می‌گوید: «does not validate that the MongoDB deployment is reachable. To verify that the deployment is reachable, call [Client.Ping].» host اشتباه، firewall یا سرور متوقف در اولین عملیات یا Ping آشکار می‌شود؛ بعد از مهلت انتخاب سرور، که اگر تغییرش ندهید 30 ثانیه است، خطای server selection می‌گیرید.

تعریف: امضا mongo.Connect(opts ...*options.ClientOptions) (*mongo.Client, error) در go.mongodb.org/mongo-driver/v2/mongo است. گزینه‌ها را با options.Client() بسازید و setterها را زنجیر کنید. .ApplyURI(uri) رشتهٔ اتصال را می‌خواند؛ مانند mongodb://host:27017/?maxPoolSize=50 یا mongodb+srv://.... ترتیب setter مهم است: مستند می‌گوید setterهای بعدی «overwrite the values from previous option setter calls, including the ApplyURI method». پس ApplyURI اول و setter صریح بعد بیاید تا کد بر URI مقدم باشد. client.Ping(ctx, readpref.Primary()) فرمانی کم‌هزینه اجرا می‌کند و در حالت دسترسی‌نداشتن، «until the client's server selection timeout expires» به خطای انتخاب سرور می‌رسد. دربارهٔ client.Disconnect(ctx) آمده: «will shut down any monitoring goroutines, close the idle connection pool, and will wait until all the in use connections have been returned». اگر ctx زودتر تمام شود، اتصال‌های در حال استفاده بسته می‌شوند و عملیات در جریان شکست می‌خورند.

main                          driver                               server
1  Connect(opts)  ──────────▶ validate options, start monitors      (no traffic needed yet)
2  Ping(ctx 2s)   ──────────▶ select a server ──────────────────▶ { ping: 1 }
3                 ◀────────── ok, or "server selection error"
4  ... handlers use the same client from many goroutines ...
5  Disconnect(ctx 5s) ──────▶ stop monitors, drain the pool, close sockets

سناریوی واقعی: یک pod در Kubernetes زودتر از سرویس دیتابیس بالا می‌آید؛ Ping با حلقهٔ retry و log روشن، مشکل را پیش از crash در اولین درخواست معلوم می‌کند. CLI یک query اجرا و با Disconnect دارای timeout کوتاه خارج می‌شود. تست نباید بدون سرور 30 ثانیه معطل بماند؛ ServerSelectionTimeout کوتاه لازم دارد و تست نمونه در 300 ms شکست می‌خورد.

گزینهSetterپیش‌فرضچه چیزی را کنترل می‌کند
رشتهٔ اتصال.ApplyURI(uri)نداردhostها، اطلاعات ورود و هر گزینهٔ URI
سقف poolSetMaxPoolSize(u) / maxPoolSize100بیشترین اتصال به هر سرور؛ با پر شدن pool صدازننده منتظر می‌ماند؛ 0 یعنی نامحدود
کف poolSetMinPoolSize(u) / minPoolSize0اتصال‌هایی که آماده نگه داشته می‌شوند
زمان بیکاریSetMaxConnIdleTime(d) / maxIdleTimeMS0، هرگززمان بستن اتصال بلااستفاده
انتخاب سرورSetServerSelectionTimeout(d)30 sمدت انتظار عملیات برای سرور قابل استفاده
بودجهٔ هر عملیاتSetTimeout(d) / timeoutMSنداردمهلت عملیات وقتی ctx مهلت ندارد
نام برنامهSetAppName(s)نداردنمایش در log سرور و currentOp
go
// Package connect builds a client with explicit timeouts and a pool size,
// verifies it with Ping and closes it with Disconnect.
package connect

import (
	"context"
	"errors"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)

// Config is what the application reads from its environment.
type Config struct {
	URI                    string
	MaxPoolSize            uint64
	MinPoolSize            uint64
	ServerSelectionTimeout time.Duration
	OperationTimeout       time.Duration // per operation, applied by the driver
	AppName                string
}

// Options turns the config into client options. ApplyURI comes first so the
// explicit setters below it win over anything in the connection string.
func Options(c Config) *options.ClientOptions {
	o := options.Client().ApplyURI(c.URI)
	if c.MaxPoolSize > 0 {
		o.SetMaxPoolSize(c.MaxPoolSize)
	}
	if c.MinPoolSize > 0 {
		o.SetMinPoolSize(c.MinPoolSize)
	}
	if c.ServerSelectionTimeout > 0 {
		o.SetServerSelectionTimeout(c.ServerSelectionTimeout)
	}
	if c.OperationTimeout > 0 {
		o.SetTimeout(c.OperationTimeout)
	}
	if c.AppName != "" {
		o.SetAppName(c.AppName)
	}
	return o
}

// Open creates the client and proves the deployment is reachable. Connect
// returns before any server is contacted, so without Ping a wrong host only
// shows up at the first query.
func Open(ctx context.Context, c Config, pingTimeout time.Duration) (*mongo.Client, error) {
	client, err := mongo.Connect(Options(c))
	if err != nil {
		return nil, fmt.Errorf("mongo connect: %w", err)
	}
	pctx, cancel := context.WithTimeout(ctx, pingTimeout)
	defer cancel()
	if err := client.Ping(pctx, readpref.Primary()); err != nil {
		// Release the background monitors even when the ping failed.
		_ = client.Disconnect(context.WithoutCancel(ctx))
		return nil, fmt.Errorf("mongo ping: %w", err)
	}
	return client, nil
}

// Close disconnects with a bounded wait; call it once, from main.
func Close(client *mongo.Client, wait time.Duration) error {
	ctx, cancel := context.WithTimeout(context.Background(), wait)
	defer cancel()
	if err := client.Disconnect(ctx); err != nil && !errors.Is(err, context.DeadlineExceeded) {
		return err
	}
	return nil
}

تست قاعدهٔ تقدم را ثابت می‌کند: URI مقدار 5، setter مقدار 20 و نتیجه 20 است. اگر override ندهید مقدار URI باقی می‌ماند. همچنین Open روی port بسته بعد از حدود 300 ms با پیام واقعی driver شکست می‌خورد: mongo ping: server selection error: context deadline exceeded, current topology: { Type: Single, Servers: [{ Addr: 127.0.0.1:1, Type: Unknown, Last error: dial tcp 127.0.0.1:1: connect: connection refused }, ] }.

go
package connect

import (
	"context"
	"testing"
	"time"
)

func TestOptionsOrderOfPrecedence(t *testing.T) {
	// The URI says 5, the explicit setter says 20: the setter is applied last.
	o := Options(Config{
		URI:                    "mongodb://127.0.0.1:27017/?maxPoolSize=5&appName=fromuri",
		MaxPoolSize:            20,
		ServerSelectionTimeout: 2 * time.Second,
		OperationTimeout:       3 * time.Second,
		AppName:                "shop-api",
	})
	if *o.MaxPoolSize != 20 {
		t.Fatalf("MaxPoolSize = %d, want 20", *o.MaxPoolSize)
	}
	if *o.ServerSelectionTimeout != 2*time.Second || *o.Timeout != 3*time.Second {
		t.Fatalf("timeouts %v %v", *o.ServerSelectionTimeout, *o.Timeout)
	}
	if *o.AppName != "shop-api" {
		t.Fatalf("AppName = %s", *o.AppName)
	}
	if len(o.Hosts) != 1 || o.Hosts[0] != "127.0.0.1:27017" {
		t.Fatalf("hosts = %v", o.Hosts)
	}
}

func TestURIValueSurvivesWhenNoOverride(t *testing.T) {
	o := Options(Config{URI: "mongodb://127.0.0.1:27017/?maxPoolSize=5"})
	if *o.MaxPoolSize != 5 {
		t.Fatalf("MaxPoolSize = %d, want 5 from the URI", *o.MaxPoolSize)
	}
}

// Nothing listens on port 1, so Ping must fail within the server selection
// timeout instead of hanging. No MongoDB server is needed for this test.
func TestOpenFailsFastWhenServerIsUnreachable(t *testing.T) {
	start := time.Now()
	client, err := Open(context.Background(), Config{
		URI:                    "mongodb://127.0.0.1:1/?directConnection=true",
		ServerSelectionTimeout: 300 * time.Millisecond,
	}, time.Second)
	if err == nil {
		_ = Close(client, time.Second)
		t.Fatal("expected an error: no server on port 1")
	}
	if d := time.Since(start); d > 3*time.Second {
		t.Fatalf("took %v, the timeouts did not apply", d)
	}
	t.Logf("failed after %v: %v", time.Since(start).Round(10*time.Millisecond), err)
}

func TestConnectRejectsBadScheme(t *testing.T) {
	if _, err := Open(context.Background(), Config{URI: "postgres://x"}, time.Second); err == nil {
		t.Fatal("a non-mongodb scheme must be rejected by Connect")
	}
}

راه‌حل / روش استفاده: یک client در main، یک Ping با timeout و defer Close. برای هر درخواست client نسازید؛ هر کدام monitor و pool خودش را شروع می‌کند. pool متعلق به client است؛ پس MaxPoolSize به‌ازای هر client و هر سرور اعمال می‌شود. برای اندازه‌گذاری در برابر سقف اتصال سرور، Connection Pooling را ببینید.

timeout مبتنی بر Context در هر فراخوانی حیاتی ​

به زبان ساده: هر متد collection یک ctx می‌گیرد. با پایان ctx، عملیات از انتظار دست می‌کشد و خطا برمی‌گرداند. محدودیت زمانی (Timeout) هر فراخوانی را شما تعیین می‌کنید، نه دیتابیس.

بدفهمی رایج: «timeout روی context، query را در سرور می‌کشد.» client دیگر منتظر نمی‌ماند و driver عملیات را رها می‌کند؛ سرور شاید آن را تمام کند یا بسته به نسخه و تنظیمات متوقفش کند. نوشتنی که ctx آن منقضی شده شاید اعمال شده باشد. timeout نوشتن را نتیجهٔ نامعلوم بدانید و نوشتن‌ها را تکرارپذیرِ بی‌اثر (Idempotent) بسازید؛ context و API Idempotency.

تعریف: driver مهلت (Deadline) روی ctx ارسالی را رعایت می‌کند. دربارهٔ SetTimeout روی client آمده «will only be honored if there is no deadline on the operation Context»؛ مهلت ctx مقدم است. mongo.IsTimeout(err) بررسی می‌کند آیا خطا در جایی از زنجیره‌اش «was caused by a timeout» یا نه.

handler (budget 800 ms)                driver                    server
1  ctx, cancel := WithTimeout(r.Context(), 300ms)
2  coll.FindOne(ctx, ...)  ─────────▶ select server, send ─────▶ run query
3  ... 300 ms pass ...
4                          ◀───────── context deadline exceeded (client stops waiting)
5  errors.Is(err, context.DeadlineExceeded) == true; mongo.IsTimeout(err) == true

سناریوی واقعی: endpoint با بودجهٔ 1 s، به دیتابیس 300 ms می‌دهد و بعد سراغ cache می‌رود. خروجی شبانه یک ctx بلندمدت و بدون timeout جدا برای هر فراخوانی دارد. نوشتن پرداخت به بودجهٔ بیشتر و کلید idempotency نیاز دارد، چون timeout آن مبهم است.

راه‌حل / روش استفاده: برای هر فراخوانی از ctx درخواست فرزند بگیرید، defer cancel() بگذارید و SetTimeout در سطح client را شبکهٔ ایمنی کدی قرار دهید که این کار را فراموش کرده است. در کد سرویس از context.TODO() استفاده نکنید؛ نمونه‌های مستند driver برای کوتاهی آن را به کار می‌برند.

نوع‌های BSON: bson.D مرتب، bson.M، bson.A، bson.E حیاتی ​

به زبان ساده: BSON قالب دودویی شبیه JSON است که MongoDB ذخیره و منتقل می‌کند. در Go چهار نوع کمکی برای نوشتن مقدارهای آن دارید. bson.D فهرست جفت‌های کلید/مقدار با ترتیب ثابت است؛ bson.M یک map در Go است که ترتیب را نگه نمی‌دارد.

بدفهمی رایج: «bson.M همان bson.D کوتاه‌تر است.» ترتیب بخشی از پروتکل MongoDB است: اولین کلید فرمان، نام فرمان است؛ ترتیب کلیدهای sort، ترتیب مرتب‌سازی است؛ ترتیب کلیدهای index هم خود تعریف index است. پیمایش map در Go ترتیب تصادفی دارد، پس driver هرجا ترتیب معنا دارد آن را رد می‌کند. Find با sort از نوع bson.M و بیش از یک کلید ErrMapForOrderedArgument می‌دهد. سورس driver «a map with more than 1 element» را نامرتب می‌داند و همین بررسی برای hint هم هست. در جاهای دیگر bson.M پذیرفته می‌شود، ولی ترتیب serialization از اجرا به اجرا فرق می‌کند. تست بستهٔ filters یک bson.M شش‌کلیدی را 200 بار serialize کرد و در اجرای ثبت‌شده 6 ترتیب گرفت؛ bson.D همیشه همان یک ترتیب را ساخت.

تعریف: bson.D برابر []bson.E، bson.E برابر struct{ Key string; Value any }، bson.M برابر map[string]any و bson.A برابر []any است. سند تودرتو یعنی bson.D داخل bson.D. بنویسید bson.D{{Key: "age", Value: bson.D{{Key: "$gt", Value: 30}}}}؛ نام فیلدها را بدهید تا go vet ایراد نگیرد. شکل بدون نام فیلد در مستند driver بررسی composites را فعال می‌کند. در v2، bson.D رابط json.Marshaler را هم پیاده می‌کند و با String() به‌شکل Extended JSON چاپ می‌شود.

موقعیتانتخابدلیل
فیلتر، update، projectionbson.Dترتیب امن و بدون تصادف
sort، کلید index، فرمانbson.D، الزامیترتیب بخشی از معناست
خواندن شکل ناشناختهbson.M یا bson.Rawترتیب مهم نیست؛ دسترسی با کلید
نتیجهٔ تایپ‌دارstruct دارای tagنام فیلد در زمان کامپایل
چند مقدار برای $in و $and[]T یا bson.Aهر دو در BSON آرایه‌اند
go
// Package filters builds query documents, projections, sorts and pages.
// Every builder returns an ordered bson.D (or an options builder) and never
// splices user input into an operator position.
package filters

import (
	"regexp"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// ByEmail matches on equality. { email: "x" } is shorthand for { email: { $eq: "x" } }.
func ByEmail(email string) bson.D {
	return bson.D{{Key: "email", Value: email}}
}

// EmailEq is the explicit $eq form.
func EmailEq(email string) bson.D {
	return bson.D{{Key: "email", Value: bson.D{{Key: "$eq", Value: email}}}}
}

// OlderThan uses $gt.
func OlderThan(age int) bson.D {
	return bson.D{{Key: "age", Value: bson.D{{Key: "$gt", Value: age}}}}
}

// InCities uses $in; an empty list matches nothing. A nil slice would be
// encoded as null by default, so it is replaced by an empty array.
func InCities(cities ...string) bson.D {
	if cities == nil {
		cities = []string{}
	}
	return bson.D{{Key: "address.city", Value: bson.D{{Key: "$in", Value: cities}}}}
}

// NameContains uses $regex with the "i" option. The user text is quoted with
// regexp.QuoteMeta so it cannot become a pattern (ReDoS, accidental wildcards).
func NameContains(text string) bson.D {
	return bson.D{{Key: "name", Value: bson.D{
		{Key: "$regex", Value: regexp.QuoteMeta(text)},
		{Key: "$options", Value: "i"},
	}}}
}

// HasLineItem uses $elemMatch: one array element must satisfy both conditions.
func HasLineItem(sku string, minQty int) bson.D {
	return bson.D{{Key: "items", Value: bson.D{{Key: "$elemMatch", Value: bson.D{
		{Key: "sku", Value: sku},
		{Key: "qty", Value: bson.D{{Key: "$gte", Value: minQty}}},
	}}}}}
}

// And combines clauses explicitly.
func And(clauses ...bson.D) bson.D {
	arr := make(bson.A, len(clauses))
	for i, c := range clauses {
		arr[i] = c
	}
	return bson.D{{Key: "$and", Value: arr}}
}

// Projection keeps only the named fields (plus _id, which is on by default).
func Projection(fields ...string) bson.D {
	p := make(bson.D, 0, len(fields))
	for _, f := range fields {
		p = append(p, bson.E{Key: f, Value: 1})
	}
	return p
}

// Sort builds an ordered sort document: the order of keys is the order of
// sorting, which is why it must be a bson.D and never a bson.M.
func Sort(keys ...Key) bson.D {
	s := make(bson.D, 0, len(keys))
	for _, k := range keys {
		dir := 1
		if k.Desc {
			dir = -1
		}
		s = append(s, bson.E{Key: k.Field, Value: dir})
	}
	return s
}

// Key is one sort key.
type Key struct {
	Field string
	Desc  bool
}

// SkipPage is limit/skip pagination: the server walks and discards
// skip documents, so page 10,000 costs 10,000 index entries.
func SkipPage(page, size int64) *options.FindOptionsBuilder {
	return options.Find().
		SetSort(Sort(Key{Field: "_id"})).
		SetSkip((page - 1) * size).
		SetLimit(size)
}

// After is range pagination on _id: "give me the next size documents after the
// last _id I saw". The cost does not grow with the page number.
func After(last bson.ObjectID, size int64) (bson.D, *options.FindOptionsBuilder) {
	filter := bson.D{}
	if !last.IsZero() {
		filter = bson.D{{Key: "_id", Value: bson.D{{Key: "$gt", Value: last}}}}
	}
	return filter, options.Find().SetSort(Sort(Key{Field: "_id"})).SetLimit(size)
}

// Resolve applies the setter functions of a builder to a plain options struct,
// which is how the tests read back what was configured.
func Resolve(b *options.FindOptionsBuilder) (*options.FindOptions, error) {
	o := &options.FindOptions{}
	for _, set := range b.List() {
		if err := set(o); err != nil {
			return nil, err
		}
	}
	return o, nil
}

راه‌حل / روش استفاده: پیش‌فرض را bson.D بگذارید و bson.M را برای خواندن‌های موردی نگه دارید. برای دیدن سند ارسالی، آن را با bson.MarshalExtJSON(v, false, false) marshal کنید؛ تست‌های این فصل روی همین رشته assertion دارند و سرور نمی‌خواهند.

نگاشت struct: tag، _id، ObjectID، omitempty، inline و زمان حیاتی ​

به زبان ساده: برچسب struct یا Struct tag به driver می‌گوید فیلد Go با چه کلیدی ذخیره شود و چه قاعده‌ای داشته باشد: اگر خالی بود حذفش کن، داخل والد بازش کن یا اصلاً ذخیره‌اش نکن. بدون tag، نام فیلد به حروف کوچک تبدیل می‌شود.

بدفهمی رایج: «omitempty هر مقدار صفر را حذف می‌کند.» عدد، boolean و string برابر مقدار صفر، slice و map خالی و pointer و interface برابر nil حذف می‌شوند. برای struct، مستند بسته فقط این حالت را خالی می‌داند: «if the struct type implements Zeroer and the IsZero method returns true». هر دو نوع time.Time و bson.ObjectID متد IsZero دارند، پس زمان صفر و id صفر حذف می‌شوند. ولی مقدار struct معمولی مانند Address به‌صورت سند فرعی خالی می‌ماند؛ برای همین User.Address یک pointer است. دام دوم: omitzero که از encoding/json می‌شناسید، در نسخهٔ v2.8.2 این بستهٔ bson یک tag معتبر نیست.

تعریف: کلید tag برابر bson است: bson:"name,option". گزینه‌ها عبارت‌اند از omitempty، minsize که int64 قابل جا شدن در int32 را به‌شکل int32 می‌نویسد، truncate که هنگام decode عدد double به integer بخش اعشاری را می‌بُرد، inline که فیلد struct یا map را در والد باز می‌کند، و نام - برای کنار گذاشتن فیلد. پیش‌فرض‌های بدون tag در مستند آمده و تست پایین هم تأییدشان می‌کند: فقط فیلد exportشده، کلید با نام lowercase فیلد، struct تعبیه‌شدهٔ بدون inline به‌شکل سند فرعی با نام lowercase نوع، و pointer برابر nil بدون omitempty به‌شکل BSON null نوشته می‌شود.

هر سند یک _id دارد. اگر ندهید، driver هنگام insert یک bson.ObjectID تولید می‌کند: مقدار 12بایتی که چهار بایت اولش زمان ساخت است و معمولاً با 24 نویسهٔ hex نشان داده می‌شود. فیلد را با bson:"_id,omitempty" علامت بزنید تا id صفر حذف شود و driver آن را پر کند؛ شناسهٔ تمام‌صفر ذخیره نشود. bson.ObjectIDFromHex شکل hex را parse می‌کند و برای ورودی خراب خطا می‌دهد؛ id ورودی از URL را همین‌طور اعتبارسنجی کنید. id.Timestamp() زمان درون id را می‌خواند.

زمان به‌شکل BSON date، یعنی میلی‌ثانیه از مبدأ Unix در UTC ذخیره می‌شود. اگر time.Time نانوثانیه داشته باشد، در رفت‌وبرگشت دقت زیر میلی‌ثانیه از بین می‌رود و location هم ذخیره نمی‌شود. اگر منطقهٔ زمانی مهم است، فیلد جدا برایش نگه دارید.

tag یا پیش‌فرضاثر در marshalاثر در unmarshalکاربرد معمول
bson:"_id,omitempty" روی bson.ObjectIDid صفر حذف و driver یک id اضافه می‌کنداز سند پر می‌شودکلید اصلی
bson:"email"کلید emailکلید email را می‌خواندنام ثابت مستقل از فیلد Go
bson:"age,omitempty"0 حذف می‌شودکلید غایب مقدار 0 باقی می‌گذاردعدد اختیاری؛ دقت کنید 0 واقعی هم گم می‌شود
bson:"address,omitempty" روی pointernil حذف می‌شودکلید غایب nil می‌ماندسند فرعی اختیاری
bson:",inline" روی struct تعبیه‌شدهفیلدهایش در سطح بالا می‌آینداز سطح بالا خوانده می‌شوندفیلدهای audit مشترک
bson:"-"هرگز نوشته نمی‌شودهرگز خوانده نمی‌شودرازها و مقدارهای موقت
bson:"n,minsize" روی int64اگر جا شود نوع BSON کوچک‌ترعادیصرفه‌جویی فضا
بدون tagنام lowercase؛ struct تعبیه‌شده سند فرعی استهمانفقط اسکریپت سریع
Go                                   BSON stored
1  ID zero, Email "a@example.test"   { email: "a@example.test", name: "Ada", created_at: Date(...) }
2  (insert) driver adds ObjectID  ──▶ { _id: ObjectId("..."), email: ..., ... }
3  (read) Decode(&u)              ──▶ u.ID = that ObjectID, u.CreatedAt truncated to milliseconds
go
// Package models shows how struct tags map Go structs to BSON documents.
package models

import (
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

// Audit is embedded with the inline option, so its fields appear at the top
// level of the document instead of under a sub-document.
type Audit struct {
	CreatedAt time.Time `bson:"created_at"`
	UpdatedAt time.Time `bson:"updated_at,omitempty"`
}

// Address is a value embedded as a sub-document.
type Address struct {
	Street  string `bson:"street"`
	City    string `bson:"city"`
	Country string `bson:"country"`
}

// User is the document stored in the users collection.
type User struct {
	// ID is the primary key. omitempty keeps a zero ObjectID out of the
	// document so that the server (or the driver) generates one on insert.
	ID      bson.ObjectID `bson:"_id,omitempty"`
	Email   string        `bson:"email"`
	Name    string        `bson:"name"`
	Age     int           `bson:"age,omitempty"`
	Tags    []string      `bson:"tags,omitempty"`
	Address *Address      `bson:"address,omitempty"`
	Audit   `bson:",inline"`

	// PasswordHash is a bcrypt hash, never the password itself.
	PasswordHash string `bson:"password_hash,omitempty"`

	// Password never reaches the database: "-" skips the field.
	Password string `bson:"-"`
}

// New returns a user stamped with now. Times are stored by MongoDB as
// milliseconds since the epoch, so sub-millisecond precision is lost.
func New(email, name string, now time.Time) User {
	return User{Email: email, Name: name, Audit: Audit{CreatedAt: now}}
}
go
package models

import (
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func mustMarshal(t *testing.T, v any) bson.Raw {
	t.Helper()
	b, err := bson.Marshal(v)
	if err != nil {
		t.Fatal(err)
	}
	return bson.Raw(b)
}

func TestZeroIDIsOmitted(t *testing.T) {
	raw := mustMarshal(t, New("a@example.test", "Ada", time.Now()))
	if _, err := raw.LookupErr("_id"); err == nil {
		t.Fatal("zero ObjectID must be omitted by omitempty")
	}
}

func TestInlineFlattensAudit(t *testing.T) {
	raw := mustMarshal(t, New("a@example.test", "Ada", time.Now()))
	if _, err := raw.LookupErr("created_at"); err != nil {
		t.Fatalf("created_at should be a top-level key: %v", err)
	}
	if _, err := raw.LookupErr("audit"); err == nil {
		t.Fatal("inline struct must not appear as a sub-document")
	}
}

func TestOmitEmptyDropsZeroTime(t *testing.T) {
	raw := mustMarshal(t, New("a@example.test", "Ada", time.Now()))
	if _, err := raw.LookupErr("updated_at"); err == nil {
		t.Fatal("zero updated_at must be omitted by omitempty (time.Time implements Zeroer)")
	}
}

func TestPasswordIsSkipped(t *testing.T) {
	u := New("a@example.test", "Ada", time.Now())
	u.Password = "secret"
	raw := mustMarshal(t, u)
	if _, err := raw.LookupErr("Password"); err == nil {
		t.Fatal("password must not be stored")
	}
	if _, err := raw.LookupErr("password"); err == nil {
		t.Fatal("password must not be stored")
	}
}

func TestRoundTripTruncatesToMilliseconds(t *testing.T) {
	now := time.Date(2026, 11, 28, 10, 30, 15, 123456789, time.UTC)
	u := New("a@example.test", "Ada", now)
	u.ID = bson.NewObjectID()
	u.Address = &Address{City: "Berlin"}
	raw := mustMarshal(t, u)
	var back User
	if err := bson.Unmarshal(raw, &back); err != nil {
		t.Fatal(err)
	}
	if back.ID != u.ID || back.Address == nil || back.Address.City != "Berlin" {
		t.Fatalf("round trip lost data: %+v", back)
	}
	want := now.Truncate(time.Millisecond)
	if !back.CreatedAt.Equal(want) {
		t.Fatalf("created_at = %v, want %v", back.CreatedAt, want)
	}
}

func TestObjectIDCarriesCreationTime(t *testing.T) {
	at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	id := bson.NewObjectIDFromTimestamp(at)
	if !id.Timestamp().Equal(at) {
		t.Fatalf("timestamp = %v, want %v", id.Timestamp(), at)
	}
	back, err := bson.ObjectIDFromHex(id.Hex())
	if err != nil || back != id {
		t.Fatalf("hex round trip failed: %v", err)
	}
	if len(id.Hex()) != 24 {
		t.Fatalf("hex length = %d, want 24", len(id.Hex()))
	}
}

// A struct without an IsZero method is never "empty": omitempty keeps it as an
// empty sub-document, which is why Address is a pointer in User.
func TestOmitEmptyKeepsPlainStructs(t *testing.T) {
	type wrap struct {
		A Address  `bson:"a,omitempty"`
		P *Address `bson:"p,omitempty"`
	}
	raw := mustMarshal(t, wrap{})
	if _, err := raw.LookupErr("a"); err != nil {
		t.Fatal("a plain struct value is kept even when zero")
	}
	if _, err := raw.LookupErr("p"); err == nil {
		t.Fatal("a nil pointer is omitted")
	}
}

// $jsonSchema bsonType "int" matches int32 only; "long" matches int64. A Go int
// that fits is written as int32, an int64 value as int64.
func TestGoIntBSONType(t *testing.T) {
	small := mustMarshal(t, bson.D{{Key: "n", Value: 5}})
	big := mustMarshal(t, bson.D{{Key: "n", Value: int64(1) << 40}})
	if got := small.Index(0).Value().Type; got != bson.TypeInt32 {
		t.Fatalf("small int type = %v, want int32", got)
	}
	if got := big.Index(0).Value().Type; got != bson.TypeInt64 {
		t.Fatalf("big int type = %v, want int64", got)
	}
}

// Without tags the driver lowercases the field name, stores an embedded struct
// as a sub-document keyed by its lowercased type name, and writes a nil pointer
// as BSON null. These are the defaults the tags above override.
func TestDefaultsWithoutTags(t *testing.T) {
	type Inner struct{ X int }
	type Plain struct {
		FullName string
		Inner
		Ptr *Address
	}
	raw := mustMarshal(t, Plain{FullName: "Ada"})
	if raw.Lookup("fullname").StringValue() != "Ada" {
		t.Fatal("default key is the lowercased field name")
	}
	if raw.Lookup("inner").Type != bson.TypeEmbeddedDocument {
		t.Fatal("an embedded struct without inline is a sub-document")
	}
	if raw.Lookup("ptr").Type != bson.TypeNull {
		t.Fatal("a nil pointer without omitempty is BSON null")
	}
}
Struct tags decide the shape of the stored documentGo struct UserID bson.ObjectID `bson:"_id,omitempty"`Email string `bson:"email"`Address *Address `bson:"address,omitempty"`Audit `bson:",inline"`Password string `bson:"-"`Age int `bson:"age,omitempty"`MarshalBSON document_id: absent, the driver adds an ObjectID on insertemail: "ada@example.test"address: absent while the pointer is nilcreated_at: Date, top level, millisecondspassword: never storedage: int32 when it fits, absent when 0Without tags: key = lowercased field name, embedded struct = sub-document, nil pointer = null.omitempty drops a plain struct value never, but drops time.Time and ObjectID when zero (they have IsZero).

سناریوی واقعی: بلوک audit شامل created_at و updated_at در ده نوع سند از طریق struct تعبیه‌شده و inline مشترک است. فیلد hash رمز روی نوع درخواست bson:"-" دارد تا تصادفی ذخیره نشود. فیلد اختیاری deleted_at با omitempty از سندهای فعال حذف می‌شود. یا _id برای سند تنظیمات یک slug رشته‌ای است؛ در این حالت فیلد string است و omitempty ندارد.

راه‌حل / روش استفاده: همهٔ فیلدها را صریح tag بزنید، کلیدها را snake_case بگذارید و id را bson.ObjectID نگه دارید مگر کلید طبیعی انتخاب بهتری باشد. تستی نگه دارید که هر مدل را marshal کند و کلیدهای مورد استفاده در query را بررسی کند؛ تست‌های نمونه همین کار را می‌کنند. ایدهٔ tag در JSON در JSON، XML و Struct Tags آمده است. tagهای json و bson جدا هستند؛ structی که از هر دو مرز عبور می‌کند هر دو را لازم دارد.

درج با InsertOne/InsertMany حیاتی ​

به زبان ساده: درج (Insert) با InsertOne یک سند ذخیره می‌کند و _id آن را می‌دهد. InsertMany فهرستی از سندها را در یک دسته می‌فرستد؛ driver فهرست خیلی بزرگ را خرد می‌کند که پایین‌تر توضیح داده می‌شود.

بدفهمی رایج: «InsertMany همه یا هیچ است.» پیش‌فرض آن ordered است و در اولین خطا می‌ایستد، اما سندهای پیش از خطا درج‌شده باقی می‌مانند. با گزینهٔ unordered ادامه می‌دهد و همهٔ شکست‌ها را گزارش می‌کند. هیچ‌کدام تراکنش نیستند.

تعریف: coll.InsertOne(ctx, doc) مقدار *InsertOneResult{InsertedID any} می‌دهد؛ برای id تولیدشده، InsertedID حاوی bson.ObjectID است. coll.InsertMany(ctx, docs) ورودی []any می‌گیرد و *InsertManyResult{InsertedIDs []any} می‌دهد. نقض نمایهٔ یکتا (Unique index) یک mongo.WriteException، یا برای چند سند mongo.BulkWriteException، با خطای نوشتن دارای کد 11000 برمی‌گرداند.

app                                   mongod
1  InsertOne(ctx, user) ────────────▶ validate, assign _id if missing
2                                     write to collection and every index
3                       ◀──────────── { acknowledged: true, insertedId: ObjectId(...) }
4  second InsertOne, same email ────▶ unique index "email_unique" violated
5                       ◀──────────── WriteException: E11000 duplicate key error (code 11000)

سناریوی واقعی: ثبت‌نام کاربر؛ مرجع جلوگیری از تکرار، unique index روی email است، نه FindOne پیش از درج که race دارد. ورود 50,000 سطر در دسته‌های 1,000تایی یا آماده‌سازی دادهٔ تست دو نمونهٔ دیگرند.

راه‌حل / روش استفاده: pointer به struct را درج کنید، id را از نتیجه بخوانید و کد 11000 را به خطای تعارض خودتان تبدیل کنید؛ مدیریت خطا. ورودی دسته‌ای را chunk کنید. هر chunk یک درخواست است؛ دسته‌های چند هزارسندی حافظه و retry را قابل کنترل نگه می‌دارند.

FindOne و ErrNoDocuments حیاتی ​

به زبان ساده: FindOne اولین سند مطابق را می‌دهد. query پیش از برگشتن FindOne اجرا می‌شود؛ SingleResult پاسخ یا خطا را نگه می‌دارد و Decode آن را داخل مقدار شما کپی می‌کند. «تطبیق پیدا نشد» خطاست، نه مقدار خالی.

بدفهمی رایج: «FindOne اگر query خراب شود خطا و اگر چیزی پیدا نشود nil می‌دهد.» خود FindOne خروجی error ندارد. نتیجه، از جمله شکست query، از SingleResult با .Decode() یا .Err() خوانده می‌شود. نبودن سند همان mongo.ErrNoDocuments با متن «mongo: no documents in result» است؛ آن را با errors.Is مقایسه کنید. «اولین» بدون sort یعنی اولین چیزی که سرور به آن برخورد کند، نه قدیمی‌ترین سند.

تعریف: امضا coll.FindOne(ctx, filter, opts...) *mongo.SingleResult است. SingleResult متدهای Decode(v)، Raw() و Err() دارد. خود FindOne پیش از برگشت، همان تابع داخلی find مورد استفادهٔ Find را اجرا و نتیجهٔ اول را می‌خواند. سورس می‌گوید اگر عملیات سندی برنگرداند، «all SingleResult methods will return ErrNoDocuments».

go
var u models.User
err := coll.FindOne(ctx, bson.D{{Key: "email", Value: email}}).Decode(&u)
switch {
case errors.Is(err, mongo.ErrNoDocuments):
	return nil, ErrNotFound // the caller's domain error
case err != nil:
	return nil, err
}

سناریوی واقعی: بارگذاری کاربر با email هنگام ورود، بارگذاری سند با _id از URL پس از ObjectIDFromHex، یا گرفتن یک سند یکتای تنظیمات.

راه‌حل / روش استفاده: ErrNoDocuments را در مرز repository تبدیل کنید تا handler HTTP مجبور به import کردن driver نباشد. اگر «اولین» معنای مشخصی دارد، SetSort را به گزینه‌ها اضافه کنید.

Find با cursor: Next، Decode، All، Close حیاتی ​

به زبان ساده: Find سندها را برنمی‌گرداند؛ مکان‌نما (Cursor) می‌دهد، یعنی handle نتیجه‌ای که سرور آن را دسته‌دسته تحویل می‌دهد. با Next جلو می‌روید، با Decode هر سند را کپی می‌کنید و در پایان cursor را می‌بندید.

بدفهمی رایج: «کل نتیجه را خواندم، پس cursor تمام است.» cursor تا تخلیه یا بسته شدن منابع سرور را نگه می‌دارد. مستند برای خواندن تک‌تک با Next می‌گوید «always close the cursor to free the resources that it consumes» و دربارهٔ Close می‌گوید «frees the resources your cursor consumes in both the client application and the MongoDB server». خود All cursor را می‌بندد: «This method will close the cursor after retrieving all documents». با این حال defer cur.Close(ctx) هزینه‌ای ندارد و بازگشت زودهنگام را هم پوشش می‌دهد.

تعریف: coll.Find(ctx, filter, opts...) (*mongo.Cursor, error). متد cur.Next(ctx) bool جلو می‌رود؛ cur.Decode(&v) یک مقدار را پر می‌کند؛ cur.Err() خطایی را می‌دهد که پیمایش را تمام کرده و باید بعد از حلقه بررسی شود. cur.All(ctx, &slice) همه را در pointer به slice decode و محتوای آن را کاملاً جایگزین می‌کند: «will be completely overwritten». cur.Close(ctx) منابع را آزاد می‌کند. نتیجهٔ خالی cursor خالی است، نه خطا.

app                                 driver                          server
1  Find(ctx, filter, limit 20) ──▶ send find ───────────────▶ run query, open cursor
2                              ◀── first batch of documents
3  Next → true, Decode × many      served from the local batch
4  Next → false at batch end   ──▶ getMore ───────────────────────▶ next batch
5  Next → false (exhausted), Err() == nil
6  Close(ctx)                  ──▶ killCursors if still open ─────▶ resources freed
روش خواندنحافظهزمان استفادهمراقب چه باشید
All داخل []Tکل نتیجه یک‌جانتیجهٔ در حد یک صفحه با limitAll نامحدود روی collection بزرگ همهٔ حافظه را مصرف می‌کند
Next + Decodeیک سند در هر مرحلهexport، migration، JSON جریانیفراموش کردن Close و Err()
Decode داخل bson.Rawبدون تبدیل structproxy عبوریparse دستی لازم است
TryNextمثل Next ولی بدون انتظار مسدودکنندهtailable cursor و change streamروی batch خالی هم false می‌دهد، نه فقط پایان

repository این فصل هر دو راه را دارد: List از All و Each از Next و Decode برای خواندن جریانی استفاده می‌کند. هر دو Close را defer و خطاها را بررسی می‌کنند.

سناریوی واقعی: endpoint فهرست با All و limit برابر 50؛ خروجی شبانهٔ ده میلیون سند با Next و نویسندهٔ جریانی؛ migrationی که همهٔ سندها را بازنویسی می‌کند.

راه‌حل / روش استفاده: پیش از All همیشه limit بدهید. برای نتیجه‌ای که می‌تواند بزرگ باشد Next/Decode بگذارید. درست پس از بررسی خطا، defer cur.Close(ctx) و پس از حلقه cur.Err() را بخوانید.

فیلترها: $eq، $gt، $in، $regex، $elemMatch حیاتی ​

به زبان ساده: فیلتر (Filter) سندی است که سندهای موردنظر شما را توصیف می‌کند. { email: "x" } یعنی email برابر x؛ عملگرها (Operators) با $ شروع می‌شوند و بقیهٔ شرط‌ها را بیان می‌کنند.

بدفهمی رایج: «بدنهٔ درخواست را داخل فیلتر می‌ریزم؛ MongoDB پاک‌سازی می‌کند.» هیچ‌چیز کلیدهای operator را پاک‌سازی نمی‌کند. مقدار JSON از نوع object به سند operator مانند { "$ne": "" } تبدیل می‌شود؛ همان تزریق operator در نمونهٔ قبل. همچنین $regex ساخته‌شده از متن کاربر الگوست، نه متن ثابت: . با هر چیزی تطبیق دارد و الگوی بد می‌تواند کند باشد.

تعریف: برابری پیش‌فرض است؛ { email: "x" } کوتاه‌شدهٔ { email: { $eq: "x" } } است. عملگرهای مقایسه $eq، $ne، $gt، $gte، $lt، $lte؛ عضویت $in و $nin؛ منطق $and، $or، $nor، $not؛ وجود فیلد $exists؛ آرایه $elemMatch، $all و $size؛ و الگوی متن $regex با $options است که i بی‌حساسیت به بزرگی حروف می‌کند. کلید نقطه‌دار مانند address.city به سند فرعی و آرایه می‌رسد. $elemMatch الزام می‌کند یک عضو آرایه همهٔ شرط‌ها را هم‌زمان داشته باشد؛ شرط‌های جدا روی آرایه چنین تضمینی نمی‌دهند.

OperatorمعناBuilder در نمونهٔ Goاستفاده از index
برابری ضمنیفیلد برابر مقدارfilters.ByEmailبله
$eqبرابری صریحfilters.EmailEqبله
$gt، $gte، $lt، $lteبازهfilters.OlderThanبله، range scan
$inبرابر یکی از مقدارهاfilters.InCitiesبله، چندنقطه‌ای
$regexالگوfilters.NameContains با escape و گزینهٔ iفقط پیشوند anchored و حساس به بزرگی حروف خوب از index استفاده می‌کند
$elemMatchیک عضو همهٔ شرط‌ها را داردfilters.HasLineItemبله، با multikey index
$andهمهٔ بندهاfilters.Andبه‌ازای هر بند
$existsحضور کلیدtyped.Field.Existsبا sparse یا partial index

فهرست خالی $in چیزی را تطبیق نمی‌دهد، ولی slice برابر nil در Go به‌طور پیش‌فرض BSON null می‌شود؛ گزینهٔ client به نام NilSliceAsEmpty این رفتار را عوض می‌کند. پس filters.InCities و typed.Field.In مقدار nil را با slice خالی جایگزین می‌کنند و تستشان {"$in":[]} را بررسی می‌کند. تست فیلترها سندهای دقیق ارسالی را تثبیت می‌کند: {"email":{"$eq":"a@example.test"}}، {"age":{"$gt":30}}، {"address.city":{"$in":["Berlin","Oslo"]}}، {"name":{"$regex":"a\\.b","$options":"i"}} که نقطه‌اش با regexp.QuoteMeta escape شده، و {"items":{"$elemMatch":{"sku":"SKU-1","qty":{"$gte":2}}}}.

سناریوی واقعی: فیلتر فروشگاه با status in (...) و total > 100؛ جست‌وجوی کاربر با بخشی از نام؛ یا «سفارش‌هایی که حداقل دو واحد SKU-1 دارند». مورد آخر $elemMatch می‌خواهد، نه دو شرط جدا که شاید روی دو خط متفاوت برقرار شوند.

راه‌حل / روش استفاده: builder ورودی تایپ‌دار Go مانند string، int و []string بگیرد، هرگز map[string]any نگیرد. ورودی regex را escape کنید و برای جست‌وجو الگوی anchored یا text index را ترجیح دهید؛ نمایه‌ها.

انتخاب فیلد و ترتیب: Projection و sort مهم ​

به زبان ساده: گزینش فیلد (Projection) می‌گوید چه فیلدهایی برگردند و مرتب‌سازی (Sort) ترتیبشان را تعیین می‌کند. سند کوچک‌تر سریع‌تر منتقل می‌شود و sort بدون index کند است.

بدفهمی رایج: «با bson.M روی دو فیلد sort می‌کنم.» map ترتیب ندارد؛ driver یک bson.M چندکلیدی برای sort را با ErrMapForOrderedArgument رد می‌کند، هم در Find و هم در FindOne. از bson.D استفاده کنید. همچنین sort روی فیلد دارای مقدار تکراری، ترتیب ثابت بین صفحه‌ها نمی‌دهد مگر آخرین کلید sort یکتا باشد.

تعریف: options.Find().SetProjection(bson.D{{Key: "email", Value: 1}}) فیلدها را شامل می‌کند و _id را هم نگه می‌دارد مگر با 0 حذفش کنید. SetSort(bson.D{{Key: "age", Value: -1}, {Key: "name", Value: 1}}) ابتدا age را نزولی و سپس name را صعودی مرتب می‌کند. SetLimit(n) و SetSkip(n) نتیجه را محدود می‌کنند. در v2 این setterها روی *options.FindOptionsBuilder هستند و Find خود builder را مستقیم می‌پذیرد.

سناریوی واقعی: autocomplete فقط name و _id لازم دارد؛ leaderboard ابتدا امتیاز نزولی و سپس id را مرتب می‌کند؛ export فیلد بزرگ payload را کنار می‌گذارد.

راه‌حل / روش استفاده: در نمونه، filters.Projection("email", "name") و filters.Sort(filters.Key{...}) سند مرتب می‌سازند. تست نشان می‌دهد {"age":-1,"name":1} به همان ترتیب نوشته‌شده بیرون می‌آید. sort بدون index پشتیبان در حافظهٔ سرور اجرا می‌شود. manual می‌گوید مرحله‌هایی که بیشتر از 100 مگابایت لازم دارند، از جمله $sort در حالت «when the sort operation is not supported by an index»، با allowDiskUse روشن یا پارامتر سرور allowDiskUseByDefault روشن، از MongoDB 6.0، فایل موقت روی دیسک می‌نویسند؛ اگر خاموش باشد خطا می‌دهند. در هر دو حالت sort نتیجهٔ بزرگ کند است؛ sort را index کنید؛ نمایه‌ها.

صفحه‌بندی: limit/skip در برابر بازهٔ _id حیاتی ​

به زبان ساده: «صفحهٔ 3» می‌تواند یعنی «40 مورد اول را رد کن، 20 مورد بگیر» یا «20 مورد بعد از آخرین چیزی که نشان دادم». روش اول با هر صفحه کندتر می‌شود؛ روش دوم نمی‌شود.

بدفهمی رایج: «skip مستقیم به صفحه می‌پرد.» سرور باید سندهای ردشده را به ترتیب sort طی کند تا به نتیجهٔ بعدی برسد؛ هزینهٔ صفحه‌های دور با offset زیاد می‌شود. manual همچنین می‌گوید پیش از skip روی فیلدی با مقدار یکتا sort کنید، وگرنه صفحه‌ها هم‌پوشانی پیدا می‌کنند یا سندی را از دست می‌دهند.

تعریف: شکل limit/skip برابر SetSort(_id).SetSkip((page-1)*size).SetLimit(size) است. صفحه‌بندی بازه‌ای (Range pagination)، که keyset یا cursor pagination هم نامیده می‌شود، آخرین _id صفحهٔ پیش را نگه می‌دارد و با { _id: { $gt: last } }، sort روی _id و limit برابر size ادامه می‌دهد. هزینه یک جست‌وجو در index است و به شمارهٔ صفحه وابسته نیست. هزینهٔ این انتخاب: پرش به «صفحهٔ 500» ندارید و کلید sort باید یکتا و indexشده باشد؛ _id همیشه هست. شکل SQL همین ایده در صفحه‌بندی Offset در برابر Keyset آمده است.

limit/skip, page 3, size 20                     range on _id, after id X, size 20
1  scan index from the start                   1  seek index to X (one B-tree descent)
2  discard 40 entries                          2  read the next 20 entries
3  return 20                                   3  return 20, remember the last _id
   cost grows with the page number                cost does not depend on the page number
جنبهlimit + skipبازه روی _id
هزینهٔ صفحهٔ Nبا N زیاد می‌شودثابت
پرش به صفحهٔ Nبلهنه، فقط بعدی/قبلی
ثبات هنگام تغییر دادهسطرها بین صفحه‌ها جابه‌جا می‌شوندثابت؛ از آخرین id دیده‌شده ادامه می‌دهد
نیاز به کلید sort یکتابله، برای ثباتبله، _id
شمارش کل در هر صفحهCountDocuments اضافهلازم نیست؛ با limit + 1 وجود صفحهٔ بعد را بفهمید
مناسب برایجدول مدیریتی کوچکfeed، API و export

تست‌ها تأیید می‌کنند SkipPage(3, 20) مقدار skip را 40 و limit را 20 می‌کند. After(last, 25) هیچ skip نمی‌گذارد، فیلتر {"_id":{"$gt":{"$oid":"65f000000000000000000001"}}} می‌سازد و برای صفحهٔ اول فیلتر خالی می‌دهد.

سناریوی واقعی: feed با اسکرول بی‌پایان و API عمومی، با token به نام next حاوی آخرین id و query بازه‌ای؛ در مقابل، جدول back-office با 300 سطر که skip برایش مناسب است.

راه‌حل / روش استفاده: پیش‌فرض را range pagination بگذارید و آخرین _id را به‌شکل token غیرشفاف encode کنید. وقتی sort روی فیلد غیریکتا مانند created_at است، با (created_at, _id) مرتب و روی هر دو فیلتر کنید.

به‌روزرسانی: UpdateOne/UpdateMany، $set، $inc، $push، $addToSet حیاتی ​

به زبان ساده: به‌روزرسانی (Update) سند دومی است که می‌گوید چه چیز عوض شود. $set مقدار می‌نویسد، $inc عدد اضافه می‌کند، $push به آرایه می‌افزاید و $addToSet فقط مقدار غایب را اضافه می‌کند.

بدفهمی رایج: «سند را می‌خوانم، struct را عوض می‌کنم و ذخیره می‌کنم؛ این update است.» بین خواندن و نوشتن، درخواست دیگری می‌تواند همان سند را تغییر دهد؛ ذخیرهٔ شما تغییر او را پاک می‌کند: به‌روزرسانی گم‌شده (Lost update). $inc محاسبه را روی سرور و برای همان سند اتمیک انجام می‌دهد. نکتهٔ دیگر: UpdateOne سند معمولی بدون operator را رد می‌کند؛ برای جایگزینی سند باید ReplaceOne بزنید.

تعریف: coll.UpdateOne(ctx, filter, update, opts...) اولین تطبیق و UpdateMany همه را تغییر می‌دهد. هر دو *UpdateResult{MatchedCount, ModifiedCount, UpsertedCount, UpsertedID} برمی‌گردانند. نبودن تطبیق خطا نیست؛ MatchedCount را بررسی کنید. عملگرها: $set، $unset، $inc، $mul، $min، $max، $push، $pull، $addToSet، $currentDate و $setOnInsert.

T1 (read-modify-write)                       T2 (read-modify-write)         document: logins = 5
1  FindOne  → logins 5                       FindOne → logins 5
2  logins = 6                                logins = 6
3  ReplaceOne(logins 6)                      ReplaceOne(logins 6)           → 6, one login lost
--- with $inc ---
1  UpdateOne({$inc: {logins: 1}})            UpdateOne({$inc: {logins: 1}}) → 7, both counted
Operatorاثردام
$setفیلدهای فهرست‌شده را تنظیم می‌کندفیلد غایب می‌سازد؛ مسیر نقطه‌دار فیلد تودرتو را تنظیم می‌کند
$incعدد اضافه می‌کنداگر فیلد نباشد آن را با همان مقدار می‌سازد
$pushاضافه می‌کند؛ تکرار مجاز استبدون محدود کردن با $slice آرایه بی‌حد رشد می‌کند
$addToSetدر صورت غیبت اضافه می‌کندکل مقدار را مقایسه می‌کند؛ ترتیب فیلدهای سند فرعی مهم است
$pullعضوهای مطابق را حذف می‌کندشرط هم می‌پذیرد، فقط مقدار نیست
$setOnInsertفقط هنگام insert در upsert اعمال می‌شوددر update نادیده گرفته می‌شود
$currentDateزمان سرور را می‌گذارداختلاف ساعت سرورهای برنامه را حذف می‌کند

بستهٔ updates هرکدام را به‌شکل bson.D مرتب می‌سازد و تست‌ها سندها را تثبیت می‌کنند: {"$inc":{"logins":1}}، {"$push":{"notes":"hello"}}، {"$addToSet":{"tags":"go"}} و {"$set":{"name":"Ada","updated_at":{"$date":"2026-01-02T03:04:05Z"}}}.

go
// Package updates builds update documents, upserts and bulk writes.
package updates

import (
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"

	"academy/mongodb-with-go/models"
)

// Rename sets two fields in one atomic document update.
func Rename(name string, now time.Time) bson.D {
	return bson.D{{Key: "$set", Value: bson.D{
		{Key: "name", Value: name},
		{Key: "updated_at", Value: now},
	}}}
}

// Inc adds delta to a numeric field atomically on the server. This is the
// fix for the read-modify-write lost update.
func Inc(field string, delta int) bson.D {
	return bson.D{{Key: "$inc", Value: bson.D{{Key: field, Value: delta}}}}
}

// Push appends to an array, duplicates allowed.
func Push(field string, v any) bson.D {
	return bson.D{{Key: "$push", Value: bson.D{{Key: field, Value: v}}}}
}

// AddToSet appends only when the value is not already present.
func AddToSet(field string, v any) bson.D {
	return bson.D{{Key: "$addToSet", Value: bson.D{{Key: field, Value: v}}}}
}

// UpsertByEmail returns the filter, update and options for "create or update
// by natural key". $setOnInsert applies only when the document is created.
func UpsertByEmail(email, name string, now time.Time) (bson.D, bson.D, *options.UpdateOneOptionsBuilder) {
	filter := bson.D{{Key: "email", Value: email}}
	update := bson.D{
		{Key: "$set", Value: bson.D{{Key: "name", Value: name}, {Key: "updated_at", Value: now}}},
		{Key: "$setOnInsert", Value: bson.D{{Key: "created_at", Value: now}}},
	}
	return filter, update, options.UpdateOne().SetUpsert(true)
}

// Counter increments a counter and returns the new value in one round trip:
// FindOneAndUpdate with ReturnDocument After.
func Counter(name string) (bson.D, bson.D, *options.FindOneAndUpdateOptionsBuilder) {
	return bson.D{{Key: "_id", Value: name}},
		Inc("seq", 1),
		options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After)
}

// SyncModels turns a batch of users into one unordered BulkWrite: replace by
// email with upsert. One round trip, partial failure reported per model.
func SyncModels(users []models.User) []mongo.WriteModel {
	out := make([]mongo.WriteModel, 0, len(users))
	for _, u := range users {
		out = append(out, mongo.NewReplaceOneModel().
			SetFilter(bson.D{{Key: "email", Value: u.Email}}).
			SetReplacement(u).
			SetUpsert(true))
	}
	return out
}

// Unordered keeps going after the first failing model.
func Unordered() *options.BulkWriteOptionsBuilder {
	return options.BulkWrite().SetOrdered(false)
}
go
package updates

import (
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"

	"academy/mongodb-with-go/models"
)

func ext(t *testing.T, v any) string {
	t.Helper()
	b, err := bson.MarshalExtJSON(v, false, false)
	if err != nil {
		t.Fatal(err)
	}
	return string(b)
}

func TestOperators(t *testing.T) {
	now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	cases := []struct {
		name string
		got  any
		want string
	}{
		{"set", Rename("Ada", now), `{"$set":{"name":"Ada","updated_at":{"$date":"2026-01-02T03:04:05Z"}}}`},
		{"inc", Inc("logins", 1), `{"$inc":{"logins":1}}`},
		{"push", Push("notes", "hello"), `{"$push":{"notes":"hello"}}`},
		{"addToSet", AddToSet("tags", "go"), `{"$addToSet":{"tags":"go"}}`},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := ext(t, c.got); got != c.want {
				t.Fatalf("got  %s\nwant %s", got, c.want)
			}
		})
	}
}

func TestUpsertUsesSetOnInsert(t *testing.T) {
	now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	f, u, o := UpsertByEmail("a@example.test", "Ada", now)
	if ext(t, f) != `{"email":"a@example.test"}` {
		t.Fatalf("filter %s", ext(t, f))
	}
	raw := bson.Raw(mustMarshal(t, u))
	if _, err := raw.LookupErr("$setOnInsert", "created_at"); err != nil {
		t.Fatal("created_at must live under $setOnInsert so updates do not overwrite it")
	}
	opts := o.List()
	if len(opts) != 1 {
		t.Fatalf("expected one option setter, got %d", len(opts))
	}
}

func mustMarshal(t *testing.T, v any) []byte {
	t.Helper()
	b, err := bson.Marshal(v)
	if err != nil {
		t.Fatal(err)
	}
	return b
}

func TestSyncModels(t *testing.T) {
	users := []models.User{
		models.New("a@example.test", "Ada", time.Now()),
		models.New("b@example.test", "Bob", time.Now()),
	}
	ms := SyncModels(users)
	if len(ms) != 2 {
		t.Fatalf("got %d models, want 2", len(ms))
	}
	for _, m := range ms {
		if _, ok := m.(*mongo.ReplaceOneModel); !ok {
			t.Fatalf("unexpected model type %T", m)
		}
	}
	bo := &options.BulkWriteOptions{}
	for _, set := range Unordered().List() {
		if err := set(bo); err != nil {
			t.Fatal(err)
		}
	}
	if bo.Ordered == nil || *bo.Ordered {
		t.Fatal("Unordered must end with Ordered=false (the builder starts at true)")
	}
}

func TestCounterReturnsAfter(t *testing.T) {
	f, u, o := Counter("invoice")
	if ext(t, f) != `{"_id":"invoice"}` || ext(t, u) != `{"$inc":{"seq":1}}` {
		t.Fatalf("unexpected %s %s", ext(t, f), ext(t, u))
	}
	if len(o.List()) != 2 {
		t.Fatalf("expected upsert and returnDocument setters, got %d", len(o.List()))
	}
}

سناریوی واقعی: شمارندهٔ like و موجودی کیف پول با $inc، ترجیحاً همراه شرط محافظ balance >= amount در فیلتر؛ فهرست tag با $addToSet؛ log فعالیت محدود به 100 عضو با $push همراه $each و $slice؛ و تازه کردن updated_at.

راه‌حل / روش استفاده: تغییر را با operator بیان کنید و شرط ایمنی را در فیلتر بگذارید؛ { _id: id, balance: { $gte: 100 } } همراه بررسی MatchedCount == 1 شکل اتمیک بررسی‌سپس‌نوشتن است. برای شکل مبتنی بر فیلد نسخه، قفل‌گذاری خوش‌بینانه و بدبینانه را ببینید.

Upsert، ReplaceOne و FindOneAndUpdate مهم ​

به زبان ساده: درج یا به‌روزرسانی (Upsert) یعنی «اگر هست تغییر بده، وگرنه بساز». ReplaceOne کل سند را عوض می‌کند. FindOneAndUpdate در یک مرحله سند را تغییر می‌دهد و نسخهٔ قدیم یا جدید را پس می‌دهد.

بدفهمی رایج: «upsert روی فیلتر غیریکتا امن است.» دو upsert هم‌زمان با یک فیلتر می‌توانند هر دو insert کنند، مگر unique index فیلدهای فیلتر را پوشش دهد. آن وقت بازنده کد 11000 می‌گیرد و باید به‌شکل update تلاش مجدد کند. همچنین ReplaceOne هر فیلدی را که سند تازه ندارد حذف می‌کند، حتی فیلدی که نویسندهٔ دیگری همین حالا اضافه کرده است.

تعریف: options.UpdateOne().SetUpsert(true) باعث می‌شود UpdateOne در نبود تطبیق insert کند و فیلدهای برابری فیلتر را پایه بگیرد. $setOnInsert مقدارهای مخصوص insert را حمل می‌کند؛ نمونه created_at را آنجا می‌گذارد تا update بعدی بازنویسی‌اش نکند. coll.ReplaceOne(ctx, filter, replacement) اولین سند مطابق را با حفظ _id عوض می‌کند. coll.FindOneAndUpdate(ctx, filter, update, options.FindOneAndUpdate().SetReturnDocument(options.After)) سند بعد از تغییر را می‌دهد؛ پیش‌فرض، نسخهٔ قبل است. FindOneAndReplace و FindOneAndDelete هم وجود دارند. همه *SingleResult می‌دهند که در نبود تطبیق، مگر در حالت upsert، ErrNoDocuments گزارش می‌کند.

عملیاتخروجیروی یک سند اتمیک است؟کاربرد
UpdateOne + SetUpsert(true)هنگام درج UpsertedIDبلهساخت یا تغییر بر اساس کلید طبیعی
ReplaceOneشمارنده‌هابلهذخیرهٔ کل سند در ویرایش back-office
FindOneAndUpdate + Afterسند جدیدبلهشمارنده، گذار وضعیت و برداشتن job
FindOneAndDeleteسند حذف‌شدهبلهبرداشتن از collection صف

تابع Counter در نمونه شمارندهٔ ترتیبی می‌سازد: فیلتر {"_id":"invoice"}، update برابر {"$inc":{"seq":1}} و گزینه‌های upsert همراه ReturnDocument(After).

سناریوی واقعی: کار همگام‌سازی که مشتری‌ها را با email upsert می‌کند؛ شمارندهٔ شمارهٔ فاکتور؛ صفی که worker با FindOneAndUpdate({status:"pending"}, {$set:{status:"running"}}) یک job در وضعیت pending را برمی‌دارد.

راه‌حل / روش استفاده: هر upsert را با unique index روی فیلدهای فیلتر همراه کنید و برای 11000 یک بار retry بگذارید. وقتی مقدار نهایی را می‌خواهید FindOneAndUpdate بزنید، نه یک FindOne جدا بعد از تغییر.

حذف: DeleteOne و DeleteMany مهم ​

به زبان ساده: حذف (Delete) اولین تطبیق یا همهٔ تطبیق‌ها را پاک می‌کند؛ تأیید دوباره‌ای در کار نیست.

بدفهمی رایج: «DeleteOne با فیلتر خالی، تا مطمئن نباشم چیزی حذف نمی‌کند.» اولین سندی را که پیدا کند حذف می‌کند. فیلتر خالی در DeleteMany همهٔ سندهای collection را پاک می‌کند و indexها می‌مانند. هر دو DeletedCount می‌دهند و هیچ‌کدام برای صفر خطا نمی‌دهند.

تعریف: coll.DeleteOne(ctx, filter) و coll.DeleteMany(ctx, filter) خروجی *DeleteResult{DeletedCount} دارند. برای حذف نرم (Soft delete)، به‌جای حذف، deleted_at را با $set تنظیم و در خواندن‌ها فیلترش می‌کنید.

سناریوی واقعی: حذف پیش‌نویس با id، پاک‌سازی دادهٔ تست، حذف GDPR با user_id و DeleteMany، یا منقضی کردن سطرهای قدیمی که برایش TTL index بهتر است؛ نمایه‌ها.

راه‌حل / روش استفاده: فیلتر را از id تایپ‌دار بسازید، نه map. برای حذف تکی DeletedCount == 0 را «پیدا نشد» بدانید؛ repository همین کار را می‌کند. تعداد حذف‌شده در DeleteMany را log کنید.

نوشتن دسته‌ای (Bulk write) مهم ​

به زبان ساده: Bulk write نوشتن‌های متفاوت، یعنی insert، update، replace و delete، را با کمترین تعداد درخواست مجاز در حد batch می‌فرستد و خلاصهٔ نتیجه را می‌دهد.

بدفهمی رایج: «bulk write تراکنش است.» یک درخواست برای حداکثر 100,000 نوشتن است. manual می‌گوید «a maximum of 100,000 writes in a single batch operation» و برای بیشتر از آن «the client driver divides the batch into smaller groups». در حالت ordered پیش‌فرض، سرور در اولین مدل ناموفق می‌ایستد و قبلی‌ها اعمال‌شده می‌مانند. با SetOrdered(false) ادامه می‌دهد و خطاها را در mongo.BulkWriteException جمع می‌کند.

تعریف: فراخوانی coll.BulkWrite(ctx, []mongo.WriteModel{...}, options.BulkWrite().SetOrdered(false)). مدل‌ها mongo.NewInsertOneModel()، NewUpdateOneModel()، NewUpdateManyModel()، NewReplaceOneModel()، NewDeleteOneModel() و NewDeleteManyModel() هستند؛ هرکدام setter زنجیره‌ای مانند SetFilter، SetUpdate، SetReplacement و SetUpsert دارند. builder با ordered=true شروع می‌شود، پس Unordered() در نمونه یک setter اضافه می‌کند و تست setterها را اعمال می‌کند تا مقدار نهایی را بخواند.

سناریوی واقعی: همگام‌سازی 10,000 مشتری از CRM با یک ReplaceOne دارای upsert به‌ازای هر سطر، unordered و دسته‌های 1,000تایی؛ اعمال رویدادهای یک روز؛ یا پاک‌سازی بعد از job.

راه‌حل / روش استفاده: ورودی را خرد کنید و وقتی نوشتن‌ها مستقل‌اند unordered بگذارید. برای شمارهٔ ورودی‌های ناموفق BulkWriteException.WriteErrors را بخوانید. mongo.IsDuplicateKeyError طبق مستندات درایور true می‌شود «if at least one of the errors is a duplicate key error»، یعنی حتی اگر فقط یکی از خطاها duplicate key باشد.

نمایه‌ها: CreateOne، unique، compound، TTL و text حیاتی ​

به زبان ساده: نمایه (Index) ساختار مرتب جانبی است که سرور با آن سند را بدون خواندن کل collection پیدا می‌کند. بدون index روی فیلد فیلتر یا sort، query کل collection را scan می‌کند.

بدفهمی رایج: «MongoDB همه‌چیز را index می‌کند.» فقط _id به‌طور پیش‌فرض index دارد. هر فیلد دیگر که روی آن فیلتر، sort یا join می‌کنید index خودش را لازم دارد؛ هر index هم کمی نوشتن را کند و حافظه مصرف می‌کند. جلوگیری واقعی از تکرار هم کار unique index است، نه FindOne پیش از insert.

تعریف: coll.Indexes().CreateOne(ctx, mongo.IndexModel{Keys: bson.D{...}, Options: options.Index()...}) یک index و CreateMany چند index می‌سازد. Keys باید bson.D مرتب باشد؛ توضیح IndexModel.Keys می‌گوید «Map types such as bson.M are not valid». ساخت دوبارهٔ index یکسان کاری نمی‌کند. تعریف متفاوت با همان نام به IndexOptionsConflict با کد 85 یا IndexKeySpecsConflict با کد 86 می‌رسد.

IndexGoهدفنکته
تک‌فیلدی (Single field)Keys: bson.D{{Key: "email", Value: 1}}برابری و بازه روی یک فیلدجهت فقط در sort چندفیلدی اهمیت دارد
یکتا (Unique)options.Index().SetUnique(true)یک سند برای هر کلیددیتابیس تحمیل می‌کند؛ نقض آن کد 11000 است
مرکب (Compound)کلیدهای customer_id، status، created_atفیلتر روی پیشوند، سپس sortترتیب کلید همان طراحی است: برابری، سپس sort، سپس بازه
انقضایی (TTL)SetExpireAfterSeconds(0) روی فیلد dateحذف سند پس از زمان مشخصکار پس‌زمینه حدود هر 60 ثانیه پاک می‌کند؛ فوری نیست
متنی (Text)Keys: name: "text", bio: "text" + SetWeightsجست‌وجوی واژه با stemmingیک text index در هر collection
جزئی (Partial)SetPartialFilterExpression(status: "unpaid")index کردن بخشی از سندهاکوچک‌تر و سریع‌تر؛ فقط وقتی query شرط فیلتر را تضمین کند استفاده می‌شود
چندکلیدی (Multikey)خودکار روی فیلد آرایهتطبیق عضوهای آرایهیک ورودی برای هر عضو؛ compound index حداکثر یک فیلد آرایه دارد

manual مربوط به TTL می‌گوید «A background thread in mongod reads the values in the index and removes expired documents from the collection» و این کار «runs every 60 seconds». یک TTL index روی expires_at با ExpireAfterSeconds(0) سند را پس از گذشتن expires_at خودش حذف می‌کند؛ برای sessionهایی با طول عمر متفاوت همین روش به کار می‌رود.

Query: { customer_id: X, status: "paid" } sort { created_at: -1 }
Index: { customer_id: 1, status: 1, created_at: -1 }
1  descend to customer_id = X            (equality)
2  descend to status = "paid"            (equality)
3  walk entries already ordered by created_at descending   (sort needs no extra step)
go
// Package indexes declares the indexes of the users, sessions and orders
// collections and creates them at start-up.
package indexes

import (
	"context"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// Users returns the indexes of the users collection.
func Users() []mongo.IndexModel {
	return []mongo.IndexModel{
		{ // unique: the database, not the application, enforces one account per email
			Keys:    bson.D{{Key: "email", Value: 1}},
			Options: options.Index().SetUnique(true).SetName("email_unique"),
		},
		{ // text: one text index per collection, weights rank name above bio
			Keys: bson.D{{Key: "name", Value: "text"}, {Key: "bio", Value: "text"}},
			Options: options.Index().SetName("name_bio_text").
				SetWeights(bson.D{{Key: "name", Value: 5}, {Key: "bio", Value: 1}}),
		},
	}
}

// Orders returns a compound index. Key order matters: equality first, then
// sort, then range (the ESR rule).
func Orders() []mongo.IndexModel {
	return []mongo.IndexModel{
		{
			Keys:    bson.D{{Key: "customer_id", Value: 1}, {Key: "status", Value: 1}, {Key: "created_at", Value: -1}},
			Options: options.Index().SetName("customer_status_created"),
		},
		{ // partial: only unpaid orders are indexed, so the index stays small
			Keys: bson.D{{Key: "created_at", Value: 1}},
			Options: options.Index().SetName("unpaid_created").
				SetPartialFilterExpression(bson.D{{Key: "status", Value: "unpaid"}}),
		},
	}
}

// Sessions returns a TTL index: the server deletes a document once the time
// in expires_at has passed (the cleaner runs about once a minute).
func Sessions() []mongo.IndexModel {
	return []mongo.IndexModel{{
		Keys:    bson.D{{Key: "expires_at", Value: 1}},
		Options: options.Index().SetName("expires_ttl").SetExpireAfterSeconds(0),
	}}
}

// Ensure creates the indexes. CreateMany is idempotent for identical
// definitions and fails with an IndexOptionsConflict (code 85) or
// IndexKeySpecsConflict (86) for a different definition under the same name.
func Ensure(ctx context.Context, c *mongo.Collection, models []mongo.IndexModel) ([]string, error) {
	return c.Indexes().CreateMany(ctx, models)
}

// Resolve applies the setters of an index options builder to a plain struct.
func Resolve(m mongo.IndexModel) (*options.IndexOptions, error) {
	o := &options.IndexOptions{}
	if m.Options == nil {
		return o, nil
	}
	for _, set := range m.Options.List() {
		if err := set(o); err != nil {
			return nil, err
		}
	}
	return o, nil
}

تست‌ها گزینه‌ها را بازخوانی و بررسی می‌کنند: index روی email یکتا و نامش email_unique است؛ text index وزن‌های {"name":5,"bio":1} دارد؛ کلیدهای compound ترتیب {"customer_id":1,"status":1,"created_at":-1} را نگه می‌دارند؛ فیلتر partial برابر {"status":"unpaid"} است؛ مقدار TTL صفر است؛ و همهٔ سندهای کلید از نوع bson.D هستند.

go
package indexes

import (
	"testing"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func keys(t *testing.T, k any) string {
	t.Helper()
	b, err := bson.MarshalExtJSON(k, false, false)
	if err != nil {
		t.Fatal(err)
	}
	return string(b)
}

func TestUniqueEmail(t *testing.T) {
	m := Users()[0]
	o, err := Resolve(m)
	if err != nil {
		t.Fatal(err)
	}
	if o.Unique == nil || !*o.Unique || *o.Name != "email_unique" {
		t.Fatalf("unexpected options %+v", o)
	}
	if keys(t, m.Keys) != `{"email":1}` {
		t.Fatalf("keys %s", keys(t, m.Keys))
	}
}

func TestTextIndexHasWeights(t *testing.T) {
	m := Users()[1]
	if keys(t, m.Keys) != `{"name":"text","bio":"text"}` {
		t.Fatalf("keys %s", keys(t, m.Keys))
	}
	o, _ := Resolve(m)
	if keys(t, o.Weights) != `{"name":5,"bio":1}` {
		t.Fatalf("weights %s", keys(t, o.Weights))
	}
}

func TestCompoundKeyOrder(t *testing.T) {
	m := Orders()[0]
	if got := keys(t, m.Keys); got != `{"customer_id":1,"status":1,"created_at":-1}` {
		t.Fatalf("key order must be preserved, got %s", got)
	}
}

func TestPartialFilter(t *testing.T) {
	o, _ := Resolve(Orders()[1])
	if keys(t, o.PartialFilterExpression) != `{"status":"unpaid"}` {
		t.Fatalf("partial filter %s", keys(t, o.PartialFilterExpression))
	}
}

func TestTTL(t *testing.T) {
	o, _ := Resolve(Sessions()[0])
	if o.ExpireAfterSeconds == nil || *o.ExpireAfterSeconds != 0 {
		t.Fatalf("expected expireAfterSeconds 0, got %+v", o.ExpireAfterSeconds)
	}
}

// A bson.M is rejected as index keys by the driver docs: key order defines the
// index. The test documents the rule instead of calling a server.
func TestKeysAreOrderedDocuments(t *testing.T) {
	for _, m := range append(Users(), Orders()...) {
		if _, ok := m.Keys.(bson.D); !ok {
			t.Fatalf("index keys must be bson.D, got %T", m.Keys)
		}
	}
}

سناریوی واقعی: email یکتا؛ compound روی (customer_id, status, created_at) برای تاریخچهٔ سفارش؛ TTL برای session و token بازیابی رمز؛ text index برای جعبهٔ جست‌وجو؛ partial index برای 2% سفارش‌های پرداخت‌نشده.

راه‌حل / روش استفاده: indexها را در شروع برنامه یا job مهاجرت بسازید، نه در handler درخواست. وقتی query کند است plan را در shell با explain ببینید؛ روش عمومی در Query Planning، EXPLAIN و Join و طراحی index در Indexing آمده است. ساخت index روی collection بزرگ سنگین است؛ آگاهانه و بیرون ساعت اوج انجامش دهید.

Pipeline تجمیع (Aggregation pipeline): $match، $group، $lookup، $unwind، $project حیاتی ​

به زبان ساده: تجمیع (Aggregate) با یک خط لوله (Aggregation pipeline) انجام می‌شود: سندها به‌ترتیب از مرحله‌های فیلتر، گروه‌بندی، تغییر شکل، join و sort عبور می‌کنند. پاسخ MongoDB به «مجموع درآمد هر مشتری» همین است.

بدفهمی رایج: «aggregation فقط برای گزارش است و ترتیب مرحله‌ها مهم نیست.» ترتیب همان کارایی است. $match در ابتدا می‌تواند index استفاده کند و کار همهٔ مرحله‌های بعد را کم کند؛ $match بعد از $group کل collection را می‌خواند. pipeline باید آرایهٔ مرتب سندهای مرحله باشد، هرگز map نیست.

تعریف: coll.Aggregate(ctx, pipeline, opts...) یک cursor می‌دهد. mongo.Pipeline همان []bson.D است؛ برای هر مرحله یک bson.D با یک کلید مانند $match، $group، $sort، $limit، $unwind، $project یا $lookup. نتیجه را با All یا Next/Decode داخل struct نتیجه بخوانید؛ در نمونه pipelines.Row است.

مرحلهکارایدهٔ SQLنکته
$matchفیلتر سندهاWHEREاول بیاید تا index استفاده کند
$groupگروه‌بندی با _id و تجمیع با $sum، $avg، $pushGROUP BY_id کلید گروه است
$sort، $limitمرتب‌سازی و بریدنORDER BY، LIMITترکیب $sort + $limit به top-N بهینه می‌شود
$unwindیک سند خروجی برای هر عضو آرایهlateral join روی آرایهpreserveNullAndEmptyArrays خالی‌ها را نگه می‌دارد
$projectشامل کردن، حذف یا محاسبهٔ فیلدفهرست SELECTتغییر نام هم می‌دهد، مانند sku: "$_id"
$lookupjoin با collection دیگرleft outer JOINنتیجه آرایهٔ as است؛ فیلد خارجی index لازم دارد
go
// Package pipelines builds aggregation pipelines.
package pipelines

import (
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

// RevenueByCustomer filters early with $match (so an index can be used),
// then groups and sorts.
func RevenueByCustomer(since time.Time) mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$match", Value: bson.D{
			{Key: "status", Value: "paid"},
			{Key: "created_at", Value: bson.D{{Key: "$gte", Value: since}}},
		}}},
		{{Key: "$group", Value: bson.D{
			{Key: "_id", Value: "$customer_id"},
			{Key: "revenue", Value: bson.D{{Key: "$sum", Value: "$total"}}},
			{Key: "orders", Value: bson.D{{Key: "$sum", Value: 1}}},
		}}},
		{{Key: "$sort", Value: bson.D{{Key: "revenue", Value: -1}}}},
		{{Key: "$limit", Value: 10}},
	}
}

// TopSKUs unwinds the embedded items array so each line becomes a document.
func TopSKUs() mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$unwind", Value: "$items"}},
		{{Key: "$group", Value: bson.D{
			{Key: "_id", Value: "$items.sku"},
			{Key: "units", Value: bson.D{{Key: "$sum", Value: "$items.qty"}}},
		}}},
		{{Key: "$project", Value: bson.D{
			{Key: "_id", Value: 0},
			{Key: "sku", Value: "$_id"},
			{Key: "units", Value: 1},
		}}},
		{{Key: "$sort", Value: bson.D{{Key: "units", Value: -1}}}},
	}
}

// Row is the shape of one TopSKUs result.
type Row struct {
	SKU   string `bson:"sku"`
	Units int64  `bson:"units"`
}

تست pipeline نام مرحله‌ها را به‌ترتیب $match,$group,$sort,$limit بررسی می‌کند و serialization کامل TopSKUs را هم تثبیت می‌کند: $unwind روی $items، $group با $items.sku و جمع $items.qty، سپس $project برای تغییر نام _id به sku، و $sort بر اساس units.

go
package pipelines

import (
	"strings"
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func TestStageOrder(t *testing.T) {
	p := RevenueByCustomer(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
	var names []string
	for _, stage := range p {
		names = append(names, stage[0].Key)
	}
	if got := strings.Join(names, ","); got != "$match,$group,$sort,$limit" {
		t.Fatalf("stages = %s", got)
	}
}

func TestPipelineSerialisesAsArray(t *testing.T) {
	b, err := bson.MarshalExtJSON(bson.M{"pipeline": TopSKUs()}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"pipeline":[{"$unwind":"$items"},{"$group":{"_id":"$items.sku","units":{"$sum":"$items.qty"}}},` +
		`{"$project":{"_id":0,"sku":"$_id","units":1}},{"$sort":{"units":-1}}]}`
	if string(b) != want {
		t.Fatalf("got  %s\nwant %s", b, want)
	}
}

سناریوی واقعی: درآمد هر مشتری در 30 روز اخیر؛ SKUهای پرفروش از خط‌های تعبیه‌شدهٔ سفارش با $unwind و بعد $group؛ صفحهٔ سفارش همراه مشتری با $lookup.

راه‌حل / روش استفاده: pipeline را در تابعی بسازید که mongo.Pipeline می‌دهد و شکل serializeشده‌اش را تست کنید. $match را اول نگه دارید؛ allowDiskUse را فقط برای گروه‌های بزرگ شناخته‌شده اضافه کنید. برای گزارش روی حجم خیلی زیاد، collection ازپیش‌تجمیع‌شده را در نظر بگیرید؛ OLTP در برابر OLAP و ذخیره‌سازی ستونی.

فیلتر تایپ‌دار با generics مهم ​

به زبان ساده: پوشش فیلد (Field wrapper) که نوع مقدار را می‌داند به کامپایلر اجازه می‌دهد Age.Eq("ten") را رد کند. هر فیلد را یک‌بار اعلام می‌کنید و فیلترها از همان تعریف‌ها ساخته می‌شوند.

بدفهمی رایج: «generics، driver را type-safe می‌کند.» داخل کلید رشته‌ای را نمی‌بیند؛ چیزی بررسی نمی‌کند که "age" واقعاً نام ذخیره‌شده است. wrapper بررسی را به یک نقطه، یعنی تعریف فیلد و تست آن، منتقل می‌کند؛ حذفش نمی‌کند.

تعریف: نوع type Field[V any] struct{ name string } با متدهای Eq، Ne، Gt، Gte، Lt، In(vs ...V) و Exists که همگی bson.D مرتب می‌دهند؛ typed.And و typed.Or بندها را ترکیب می‌کنند. پارامتر نوع جنریک از Go 1.18 آمده است؛ Generics. فیلدها را متغیر سطح package تعریف کنید: var Age = typed.F[int]("age").

go
// Package typed makes filter values type-checked at compile time with generics.
package typed

import "go.mongodb.org/mongo-driver/v2/bson"

// Field is a document field whose values have type V.
type Field[V any] struct{ name string }

// F declares a field. Declare each field once, as a package-level variable.
func F[V any](name string) Field[V] { return Field[V]{name: name} }

// Name returns the dotted path of the field.
func (f Field[V]) Name() string { return f.name }

func (f Field[V]) op(op string, v any) bson.D {
	return bson.D{{Key: f.name, Value: bson.D{{Key: op, Value: v}}}}
}

// Eq matches equal values.
func (f Field[V]) Eq(v V) bson.D { return f.op("$eq", v) }

// Ne matches different values.
func (f Field[V]) Ne(v V) bson.D { return f.op("$ne", v) }

// Gt matches greater values.
func (f Field[V]) Gt(v V) bson.D { return f.op("$gt", v) }

// Gte matches greater or equal values.
func (f Field[V]) Gte(v V) bson.D { return f.op("$gte", v) }

// Lt matches smaller values.
func (f Field[V]) Lt(v V) bson.D { return f.op("$lt", v) }

// In matches any of the values. With no values the filter matches nothing: a
// nil slice would encode as null, so it is replaced by an empty array.
func (f Field[V]) In(vs ...V) bson.D {
	if vs == nil {
		vs = []V{}
	}
	return f.op("$in", vs)
}

// Exists matches documents that have (or lack) the field.
func (f Field[V]) Exists(yes bool) bson.D { return f.op("$exists", yes) }

// And joins clauses with $and.
func And(clauses ...bson.D) bson.D {
	arr := make(bson.A, len(clauses))
	for i, c := range clauses {
		arr[i] = c
	}
	return bson.D{{Key: "$and", Value: arr}}
}

// Or joins clauses with $or.
func Or(clauses ...bson.D) bson.D {
	arr := make(bson.A, len(clauses))
	for i, c := range clauses {
		arr[i] = c
	}
	return bson.D{{Key: "$or", Value: arr}}
}
go
package typed

import (
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

var (
	Email     = F[string]("email")
	Age       = F[int]("age")
	CreatedAt = F[time.Time]("created_at")
)

func ext(t *testing.T, v any) string {
	t.Helper()
	b, err := bson.MarshalExtJSON(v, false, false)
	if err != nil {
		t.Fatal(err)
	}
	return string(b)
}

func TestTypedFilters(t *testing.T) {
	f := And(Email.Eq("a@example.test"), Age.Gte(18), Age.In(18, 21, 30))
	want := `{"$and":[{"email":{"$eq":"a@example.test"}},{"age":{"$gte":18}},{"age":{"$in":[18,21,30]}}]}`
	if got := ext(t, f); got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

func TestTimeValuesBecomeDates(t *testing.T) {
	at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	got := ext(t, CreatedAt.Lt(at))
	want := `{"created_at":{"$lt":{"$date":"2026-01-02T03:04:05Z"}}}`
	if got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

func TestOr(t *testing.T) {
	got := ext(t, Or(Age.Lt(18), Email.Exists(false)))
	want := `{"$or":[{"age":{"$lt":18}},{"email":{"$exists":false}}]}`
	if got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

// Age.Eq("x") does not compile: the compiler rejects a string for Field[int].
func TestNameKeepsDottedPath(t *testing.T) {
	if F[string]("address.city").Name() != "address.city" {
		t.Fatal("dotted paths are kept as is")
	}
}

func TestEmptyInIsEmptyArray(t *testing.T) {
	want := `{"age":{"$in":[]}}`
	if got := ext(t, Age.In()); got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

تست‌ها {"$and":[{"email":{"$eq":"a@example.test"}},{"age":{"$gte":18}},{"age":{"$in":[18,21,30]}}]} را تثبیت می‌کنند و نشان می‌دهند time.Time به BSON date تبدیل می‌شود: {"created_at":{"$lt":{"$date":"2026-01-02T03:04:05Z"}}}.

سناریوی واقعی: سرویسی که فیلتر محصول، سفارش و کاربر را در بیست جا می‌سازد؛ code reviewی که دیگر لازم نیست املای operator را در هر نقطه بررسی کند.

راه‌حل / روش استفاده: برای هر نوع سند یک fields.go داشته باشید و تعریف‌های تایپ‌دار را کنار struct نگه دارید. تستی اضافه کنید که struct نمونه را marshal کند و مطمئن شود هر نام اعلام‌شده کلیدی در نتیجه است. این‌گونه تغییر نام tag تست را خراب می‌کند، نه production را.

Repository جنریک: Repository[T] حیاتی ​

به زبان ساده: مخزن داده (Repository) یک نوع کوچک به نام Repository[T] است که درج، گرفتن، فهرست کردن، تغییر، حذف و شمارش سند هر نوع T را بلد است؛ مدیریت خطا را یک‌بار می‌نویسید.

بدفهمی رایج: «repository جنریک MongoDB را پنهان می‌کند، پس دیتابیس را راحت عوض می‌کنم.» نوع‌ها و خطاهای driver را پنهان می‌کند، نه مدل را. وجود فیلتر bson.D در امضا یعنی MongoDB. وظیفهٔ این لایه نگاشت یکسان خطا، مدیریت درست cursor و ایجاد مرز تست است. ORM هم نیست؛ نه change tracking دارد نه lazy loading.

تعریف: repository به interface کوچکی به نام Collection با متدهای InsertOne، FindOne، Find، UpdateOne، DeleteOne و CountDocuments وابسته است. امضاها دقیقاً با *mongo.Collection برابرند؛ assertion زمان کامپایل var _ Collection = (*mongo.Collection)(nil) این را ثابت می‌کند. Get مرحلهٔ decode داخل T را انجام می‌دهد: var out T; FindOne(...).Decode(&out). متد List از Cursor.All داخل []T و Each از Next و Decode استفاده می‌کند. mapErr خطای mongo.ErrNoDocuments را به ErrNotFound و duplicate key را به ErrConflict تبدیل و با %w: %w wrap می‌کند تا خطای اصلی در زنجیره بماند؛ چند %w به Go 1.20 یا جدیدتر نیاز دارد.

caller                         Repository[User]                    Collection
1  Get(ctx, filter) ─────────▶ var out User; FindOne(ctx, filter) ─▶ SingleResult
2                              Decode(&out) fills out
3                              err == mongo.ErrNoDocuments ?
4  ◀──────── ErrNotFound (wraps the driver error) ── yes
5  ◀──────── &out ───────────────────────────────────────────────── no
go
// Package repo is a small generic repository over a MongoDB collection.
// It depends on the Collection interface, which *mongo.Collection satisfies,
// so the logic can be tested without a server.
package repo

import (
	"context"
	"errors"
	"fmt"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// Domain errors: callers match these, never driver errors.
var (
	ErrNotFound = errors.New("repo: not found")
	ErrConflict = errors.New("repo: duplicate key")
)

// Collection is the subset of *mongo.Collection the repository uses.
type Collection interface {
	InsertOne(ctx context.Context, document any, opts ...options.Lister[options.InsertOneOptions]) (*mongo.InsertOneResult, error)
	FindOne(ctx context.Context, filter any, opts ...options.Lister[options.FindOneOptions]) *mongo.SingleResult
	Find(ctx context.Context, filter any, opts ...options.Lister[options.FindOptions]) (*mongo.Cursor, error)
	UpdateOne(ctx context.Context, filter any, update any, opts ...options.Lister[options.UpdateOneOptions]) (*mongo.UpdateResult, error)
	DeleteOne(ctx context.Context, filter any, opts ...options.Lister[options.DeleteOneOptions]) (*mongo.DeleteResult, error)
	CountDocuments(ctx context.Context, filter any, opts ...options.Lister[options.CountOptions]) (int64, error)
}

var _ Collection = (*mongo.Collection)(nil)

// Repository stores documents of type T.
type Repository[T any] struct {
	coll Collection
}

// New wraps a collection.
func New[T any](c Collection) *Repository[T] { return &Repository[T]{coll: c} }

// Insert stores doc and returns the generated _id.
func (r *Repository[T]) Insert(ctx context.Context, doc *T) (bson.ObjectID, error) {
	res, err := r.coll.InsertOne(ctx, doc)
	if err != nil {
		return bson.ObjectID{}, mapErr(err)
	}
	id, ok := res.InsertedID.(bson.ObjectID)
	if !ok {
		return bson.ObjectID{}, fmt.Errorf("repo: _id is %T, not ObjectID", res.InsertedID)
	}
	return id, nil
}

// Get returns the first document that matches. Decode into T is the generic
// step: the driver fills a fresh T for every call.
func (r *Repository[T]) Get(ctx context.Context, filter bson.D) (*T, error) {
	var out T
	if err := r.coll.FindOne(ctx, filter).Decode(&out); err != nil {
		return nil, mapErr(err)
	}
	return &out, nil
}

// List reads every match into memory with Cursor.All. Cap it with Limit.
func (r *Repository[T]) List(ctx context.Context, filter bson.D, opts ...options.Lister[options.FindOptions]) ([]T, error) {
	cur, err := r.coll.Find(ctx, filter, opts...)
	if err != nil {
		return nil, mapErr(err)
	}
	defer cur.Close(ctx)
	var out []T
	if err := cur.All(ctx, &out); err != nil {
		return nil, mapErr(err)
	}
	return out, nil
}

// Each streams matches one by one with Next and Decode, so memory stays flat.
func (r *Repository[T]) Each(ctx context.Context, filter bson.D, fn func(T) error, opts ...options.Lister[options.FindOptions]) error {
	cur, err := r.coll.Find(ctx, filter, opts...)
	if err != nil {
		return mapErr(err)
	}
	defer cur.Close(ctx)
	for cur.Next(ctx) {
		var item T
		if err := cur.Decode(&item); err != nil {
			return mapErr(err)
		}
		if err := fn(item); err != nil {
			return err
		}
	}
	return mapErr(cur.Err())
}

// Update applies an update document to the first match. A match count of zero
// is ErrNotFound, not success.
func (r *Repository[T]) Update(ctx context.Context, filter, update bson.D) error {
	res, err := r.coll.UpdateOne(ctx, filter, update)
	if err != nil {
		return mapErr(err)
	}
	if res.MatchedCount == 0 {
		return ErrNotFound
	}
	return nil
}

// Delete removes the first match; zero deleted is ErrNotFound.
func (r *Repository[T]) Delete(ctx context.Context, filter bson.D) error {
	res, err := r.coll.DeleteOne(ctx, filter)
	if err != nil {
		return mapErr(err)
	}
	if res.DeletedCount == 0 {
		return ErrNotFound
	}
	return nil
}

// Count returns the exact number of matches.
func (r *Repository[T]) Count(ctx context.Context, filter bson.D) (int64, error) {
	n, err := r.coll.CountDocuments(ctx, filter)
	return n, mapErr(err)
}

// mapErr turns driver errors into domain errors and keeps the original
// error in the chain for logging.
func mapErr(err error) error {
	switch {
	case err == nil:
		return nil
	case errors.Is(err, mongo.ErrNoDocuments):
		return fmt.Errorf("%w: %w", ErrNotFound, err)
	case mongo.IsDuplicateKeyError(err):
		return fmt.Errorf("%w: %w", ErrConflict, err)
	default:
		return err
	}
}

فایدهٔ طراحی در بدل تست (Test double) روشن می‌شود: fake رابط Collection را پیاده می‌کند و با سازنده‌های خود driver، یعنی mongo.NewSingleResultFromDocument و mongo.NewCursorFromDocuments، نتیجه می‌سازد. بنابراین بدون سرور، decode واقعی BSON اجرا می‌شود. تست‌ها decode داخل T، تبدیل ErrNoDocuments به ErrNotFound با حفظ دسترسی به خطای driver از طریق errors.Is، تبدیل mongo.WriteException ساخته‌شده با کد 11000 به ErrConflict با true ماندن mongo.IsDuplicateKeyError از پشت wrap، رفتار List و Each، گزارش نبودن تطبیق در update و delete، و استفاده از همان repository برای نوع دوم را پوشش می‌دهند.

go
package repo

import (
	"context"
	"errors"
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"

	"academy/mongodb-with-go/models"
)

// fake implements Collection without a server. Documents come back through
// the driver's own constructors, so Decode and All run the real BSON codecs.
type fake struct {
	docs      []any
	insertErr error
	updated   int64
	deleted   int64
	lastFind  any
}

func (f *fake) InsertOne(_ context.Context, doc any, _ ...options.Lister[options.InsertOneOptions]) (*mongo.InsertOneResult, error) {
	if f.insertErr != nil {
		return nil, f.insertErr
	}
	return &mongo.InsertOneResult{InsertedID: bson.NewObjectID()}, nil
}

func (f *fake) FindOne(_ context.Context, filter any, _ ...options.Lister[options.FindOneOptions]) *mongo.SingleResult {
	f.lastFind = filter
	if len(f.docs) == 0 {
		return mongo.NewSingleResultFromDocument(bson.D{}, mongo.ErrNoDocuments, nil)
	}
	return mongo.NewSingleResultFromDocument(f.docs[0], nil, nil)
}

func (f *fake) Find(_ context.Context, filter any, _ ...options.Lister[options.FindOptions]) (*mongo.Cursor, error) {
	f.lastFind = filter
	return mongo.NewCursorFromDocuments(f.docs, nil, nil)
}

func (f *fake) UpdateOne(context.Context, any, any, ...options.Lister[options.UpdateOneOptions]) (*mongo.UpdateResult, error) {
	return &mongo.UpdateResult{MatchedCount: f.updated}, nil
}

func (f *fake) DeleteOne(context.Context, any, ...options.Lister[options.DeleteOneOptions]) (*mongo.DeleteResult, error) {
	return &mongo.DeleteResult{DeletedCount: f.deleted}, nil
}

func (f *fake) CountDocuments(context.Context, any, ...options.Lister[options.CountOptions]) (int64, error) {
	return int64(len(f.docs)), nil
}

func users(n int) []any {
	out := make([]any, n)
	for i := range out {
		u := models.New("u@example.test", "User", time.Now())
		u.ID = bson.NewObjectID()
		out[i] = u
	}
	return out
}

func TestGetDecodesIntoT(t *testing.T) {
	r := New[models.User](&fake{docs: users(1)})
	u, err := r.Get(context.Background(), bson.D{{Key: "email", Value: "u@example.test"}})
	if err != nil {
		t.Fatal(err)
	}
	if u.Email != "u@example.test" || u.ID.IsZero() {
		t.Fatalf("decoded %+v", u)
	}
}

func TestGetMapsNoDocumentsToNotFound(t *testing.T) {
	r := New[models.User](&fake{})
	_, err := r.Get(context.Background(), bson.D{})
	if !errors.Is(err, ErrNotFound) {
		t.Fatalf("want ErrNotFound, got %v", err)
	}
	if !errors.Is(err, mongo.ErrNoDocuments) {
		t.Fatal("the original driver error must stay in the chain")
	}
}

func TestInsertMapsDuplicateKey(t *testing.T) {
	dup := mongo.WriteException{WriteErrors: mongo.WriteErrors{{Code: 11000, Message: "E11000 duplicate key error"}}}
	r := New[models.User](&fake{insertErr: dup})
	u := models.New("a@example.test", "Ada", time.Now())
	_, err := r.Insert(context.Background(), &u)
	if !errors.Is(err, ErrConflict) {
		t.Fatalf("want ErrConflict, got %v", err)
	}
	if !mongo.IsDuplicateKeyError(err) {
		t.Fatal("IsDuplicateKeyError must still work through the wrap")
	}
}

func TestInsertReturnsObjectID(t *testing.T) {
	r := New[models.User](&fake{})
	u := models.New("a@example.test", "Ada", time.Now())
	id, err := r.Insert(context.Background(), &u)
	if err != nil || id.IsZero() {
		t.Fatalf("id=%v err=%v", id, err)
	}
}

func TestListAndEach(t *testing.T) {
	r := New[models.User](&fake{docs: users(3)})
	all, err := r.List(context.Background(), bson.D{})
	if err != nil || len(all) != 3 {
		t.Fatalf("List: %d docs, err %v", len(all), err)
	}
	n := 0
	err = r.Each(context.Background(), bson.D{}, func(models.User) error { n++; return nil })
	if err != nil || n != 3 {
		t.Fatalf("Each visited %d, err %v", n, err)
	}
	stop := errors.New("stop")
	err = r.Each(context.Background(), bson.D{}, func(models.User) error { return stop })
	if !errors.Is(err, stop) {
		t.Fatalf("callback error must be returned, got %v", err)
	}
}

func TestUpdateAndDeleteReportMissing(t *testing.T) {
	r := New[models.User](&fake{})
	if err := r.Update(context.Background(), bson.D{}, bson.D{}); !errors.Is(err, ErrNotFound) {
		t.Fatalf("update: %v", err)
	}
	if err := r.Delete(context.Background(), bson.D{}); !errors.Is(err, ErrNotFound) {
		t.Fatalf("delete: %v", err)
	}
	r = New[models.User](&fake{updated: 1, deleted: 1})
	if err := r.Update(context.Background(), bson.D{}, bson.D{}); err != nil {
		t.Fatal(err)
	}
	if err := r.Delete(context.Background(), bson.D{}); err != nil {
		t.Fatal(err)
	}
}

func TestCount(t *testing.T) {
	r := New[models.User](&fake{docs: users(2)})
	n, err := r.Count(context.Background(), bson.D{})
	if err != nil || n != 2 {
		t.Fatalf("count %d err %v", n, err)
	}
}

// The repository is generic: the same code works for any document type.
func TestSameRepositoryForAnotherType(t *testing.T) {
	type note struct {
		ID   bson.ObjectID `bson:"_id"`
		Text string        `bson:"text"`
	}
	r := New[note](&fake{docs: []any{note{ID: bson.NewObjectID(), Text: "hi"}}})
	got, err := r.Get(context.Background(), bson.D{})
	if err != nil || got.Text != "hi" {
		t.Fatalf("got %+v err %v", got, err)
	}
}
One interface, two implementationsHTTP handlerServiceRepository of TDecode into T, map errorsCollection interfaceFindOne, Find, InsertOne ...mongo.Collectionproduction, needs mongodfaketests1 The repository imports no server code: it only needs the six methods in the interface.2 The fake builds results with mongo.NewCursorFromDocuments, so BSON decoding is the real one.3 Behaviour only a server can show (indexes, transactions) stays in integration tests.

سناریوی واقعی: ده collection با یک نوع repository؛ لایهٔ service متکی به interface به نام UserStore که *Repository[User] آن را برآورده می‌کند؛ تست handler با تزریق store جعلی؛ Mocking با Interface.

راه‌حل / روش استفاده: لایه را نازک نگه دارید و داخلش query builder نسازید. متد مخصوص collection مانند FindByEmail را در wrapperی قرار دهید که *Repository[User] را embed می‌کند. تراکنش بیرون repository بماند؛ چون چند repository را در بر می‌گیرد، لایهٔ service باید آن را آغاز کند؛ تراکنش‌ها.

رابطه‌ها: تعبیه، ارجاع، $lookup و denormalization حیاتی ​

به زبان ساده: رابطهٔ یک‌به‌چند در SQL دو جدول و یک join است. در MongoDB انتخاب می‌کنید: فرزندها داخل سند والد باشند، یعنی تعبیه (Embedding)، یا فرزند id والد را داشته باشد، یعنی ارجاع (Referencing)، و موقع نیاز join کنید.

بدفهمی رایج: «روش MongoDB تعبیه است، پس همه‌چیز را embed می‌کنم.» آرایهٔ تعبیه‌شدهٔ بی‌حد به سقف 16 MiB سند می‌رسد؛ «Documents in MongoDB must be smaller than 16 mebibytes». هر تغییر بازنویسی سند بزرگ می‌شود و چنین آرایه‌ای قابل صفحه‌بندی نیست. «MongoDB join ندارد، پس ارجاع نمی‌دهم» هم غلط است؛ $lookup وجود دارد و دادهٔ چندبه‌چند جایگاهش collectionهای جداست.

تعریف: راهنمای manual این است: برای رابطهٔ «contains» و یک‌به‌چندی که فرزند در زمینهٔ والد دیده می‌شود، embed کنید. وقتی تعبیه «would result in duplication of data» و آن داده «frequently changes»، برای «complex many-to-many relationships»، یا وقتی «frequently query the related entity on its own»، ارجاع بدهید. تعبیه را غیرنرمال‌سازی (Denormalization) هم می‌نامند؛ manual مدل تعبیه‌شده را «often considered denormalized because frequently-accessed data is duplicated» توصیف می‌کند. ارجاع دادهٔ نرمال‌شده می‌دهد. تصویر لحظه‌ای (Snapshot)، مثل کپی نام مشتری داخل سفارش، denormalization هدفمند است: سفارش باید نام زمان خرید را نشان دهد.

تصمیمEmbedReferenceکپی Snapshot
تقریباً همیشه با هم خوانده می‌شوندبهترین؛ یک خواندندو خواندن یا $lookupبهترین
تعداد فرزندمحدود، در حد ده‌هانامحدودموضوعیت ندارد
فرزند پرتغییر و مشترک بین والدهابد؛ بازنویسی فراوانبهترینکهنه می‌ماند مگر کپی‌ها بازنویسی شوند
تغییر اتمیک والد و فرزندیک سند، اتمیکتراکنش لازم داردیک سند
query مستقل فرزنددشوار با $unwindطبیعینه
رشد سندخطر سقف 16 MiBنداردکم

نمونه یک Order می‌سازد که Items را embed، مشتری را با customer_id reference و snapshot نام را در customer.name نگه می‌دارد. تست ثابت می‌کند سفارش یک سند با آرایهٔ items دو عضوی است، ارجاع مشتری BSON ObjectID است و نام snapshot ذخیره می‌شود.

go
// Package relations contrasts embedding and referencing and shows $lookup and
// the cost of denormalisation.
package relations

import (
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

// Customer lives in its own collection and is referenced by orders.
type Customer struct {
	ID    bson.ObjectID `bson:"_id,omitempty"`
	Name  string        `bson:"name"`
	Email string        `bson:"email"`
}

// Item is embedded: it has no life outside its order, is read together with
// it, and is bounded (an order has tens of lines, not millions).
type Item struct {
	SKU   string `bson:"sku"`
	Qty   int    `bson:"qty"`
	Price int64  `bson:"price_cents"`
}

// CustomerSnapshot is denormalised: a copy of the fields the order page shows,
// frozen at purchase time. The reference stays for everything else.
type CustomerSnapshot struct {
	Name string `bson:"name"`
}

// Order embeds items, references the customer and snapshots the name.
type Order struct {
	ID         bson.ObjectID    `bson:"_id,omitempty"`
	CustomerID bson.ObjectID    `bson:"customer_id"`
	Customer   CustomerSnapshot `bson:"customer"`
	Items      []Item           `bson:"items"`
	Status     string           `bson:"status"`
	CreatedAt  time.Time        `bson:"created_at"`
}

// WithCustomer joins one order to its customer document. $lookup is a
// left outer join; $unwind turns the one-element array into an object.
func WithCustomer(orderID bson.ObjectID) mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$match", Value: bson.D{{Key: "_id", Value: orderID}}}},
		{{Key: "$lookup", Value: bson.D{
			{Key: "from", Value: "customers"},
			{Key: "localField", Value: "customer_id"},
			{Key: "foreignField", Value: "_id"},
			{Key: "as", Value: "customer_doc"},
		}}},
		{{Key: "$unwind", Value: bson.D{
			{Key: "path", Value: "$customer_doc"},
			{Key: "preserveNullAndEmptyArrays", Value: true},
		}}},
		{{Key: "$project", Value: bson.D{
			{Key: "status", Value: 1},
			{Key: "items", Value: 1},
			{Key: "customer_email", Value: "$customer_doc.email"},
		}}},
	}
}

// RecentOrdersPerCustomer is the pipeline form of $lookup: a sub-pipeline with
// let variables, so the joined side can be filtered, sorted and limited.
func RecentOrdersPerCustomer(limit int64) mongo.Pipeline {
	return mongo.Pipeline{
		{{Key: "$lookup", Value: bson.D{
			{Key: "from", Value: "orders"},
			{Key: "let", Value: bson.D{{Key: "cid", Value: "$_id"}}},
			{Key: "pipeline", Value: mongo.Pipeline{
				{{Key: "$match", Value: bson.D{{Key: "$expr", Value: bson.D{
					{Key: "$eq", Value: bson.A{"$customer_id", "$$cid"}},
				}}}}},
				{{Key: "$sort", Value: bson.D{{Key: "created_at", Value: -1}}}},
				{{Key: "$limit", Value: limit}},
			}},
			{Key: "as", Value: "recent_orders"},
		}}},
	}
}

// RenameEverywhere is the price of the snapshot: when a customer changes name
// and you want the snapshot to follow, every order must be rewritten.
func RenameEverywhere(customerID bson.ObjectID, name string) (filter, update bson.D) {
	return bson.D{{Key: "customer_id", Value: customerID}},
		bson.D{{Key: "$set", Value: bson.D{{Key: "customer.name", Value: name}}}}
}

$lookup روی سرور join می‌کند: from نام collection است و localField، foreignField و as که آرایهٔ نتیجه است، بقیهٔ اجزا هستند. تست کل pipeline را تثبیت می‌کند: $match روی id سفارش، $lookup از customers، $unwind با preserveNullAndEmptyArrays: true تا سفارش بی‌مشتری هم برگردد، و $project. شکل دوم let و pipeline داخلی دارد؛ سمت join می‌تواند فیلتر، sort و limit داشته باشد، مثلاً سه سفارش اخیر هر مشتری. هزینهٔ snapshot در RenameEverywhere دیده می‌شود: یک UpdateMany که وقتی تصمیم می‌گیرید کپی‌ها هم به‌روز شوند، همهٔ سفارش‌های مشتری را بازنویسی می‌کند.

go
package relations

import (
	"strings"
	"testing"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func TestOrderIsOneDocument(t *testing.T) {
	cid := bson.NewObjectID()
	o := Order{
		CustomerID: cid,
		Customer:   CustomerSnapshot{Name: "Ada"},
		Items:      []Item{{SKU: "A", Qty: 1, Price: 500}, {SKU: "B", Qty: 2, Price: 250}},
		Status:     "paid",
		CreatedAt:  time.Now(),
	}
	b, err := bson.Marshal(o)
	if err != nil {
		t.Fatal(err)
	}
	raw := bson.Raw(b)
	items, err := raw.LookupErr("items")
	if err != nil {
		t.Fatal(err)
	}
	vals, _ := items.Array().Values()
	if len(vals) != 2 {
		t.Fatalf("items are embedded in the order, got %d", len(vals))
	}
	ref := raw.Lookup("customer_id")
	if ref.Type != bson.TypeObjectID || ref.ObjectID() != cid {
		t.Fatal("customer is referenced by ObjectID, not embedded")
	}
	if raw.Lookup("customer", "name").StringValue() != "Ada" {
		t.Fatal("snapshot name expected")
	}
}

func TestLookupStages(t *testing.T) {
	id, _ := bson.ObjectIDFromHex("65f000000000000000000001")
	p := WithCustomer(id)
	b, err := bson.MarshalExtJSON(bson.M{"p": p}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"p":[{"$match":{"_id":{"$oid":"65f000000000000000000001"}}},` +
		`{"$lookup":{"from":"customers","localField":"customer_id","foreignField":"_id","as":"customer_doc"}},` +
		`{"$unwind":{"path":"$customer_doc","preserveNullAndEmptyArrays":true}},` +
		`{"$project":{"status":1,"items":1,"customer_email":"$customer_doc.email"}}]}`
	if string(b) != want {
		t.Fatalf("got  %s\nwant %s", b, want)
	}
}

func TestPipelineLookupHasLet(t *testing.T) {
	b, err := bson.MarshalExtJSON(bson.M{"p": RecentOrdersPerCustomer(3)}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	for _, frag := range []string{`"let":{"cid":"$_id"}`, `"$$cid"`, `"$limit":3`} {
		if !strings.Contains(string(b), frag) {
			t.Fatalf("missing %s in %s", frag, b)
		}
	}
}

func TestRenameEverywhere(t *testing.T) {
	id, _ := bson.ObjectIDFromHex("65f000000000000000000001")
	f, u := RenameEverywhere(id, "Ada L.")
	fb, _ := bson.MarshalExtJSON(f, false, false)
	ub, _ := bson.MarshalExtJSON(u, false, false)
	if string(fb) != `{"customer_id":{"$oid":"65f000000000000000000001"}}` || string(ub) != `{"$set":{"customer.name":"Ada L."}}` {
		t.Fatalf("%s %s", fb, ub)
	}
}
Embed what is read together, reference what lives on its ownorders (one document)_id, status, created_atitems: [ sku, qty, price_cents ], [ sku, qty, price_cents ]embedded: bounded, read with the order, one atomic writecustomer: name (snapshot copy), customer_id (reference)the copy is fast to read and stale after a renamecustomers (own collection)_id, name, emailqueried on its own,changes often,shared by many orders$lookup1 Embed: contains-relationships, bounded arrays, data always read together. Limit: a document stays under 16 MiB.2 Reference: data that changes often, many-to-many, or queried by itself. Cost: a second query or a $lookup stage.3 Snapshot: copy the few fields a screen needs; decide who updates the copy when the source changes.4 An unbounded array (comments, events) is the classic embedding mistake: move it to its own collection.

برای کسی که از SQL می‌آید، همین صفحهٔ سفارش در schema رابطه‌ای با join ساخته می‌شود؛ در MongoDB یک خواندن سند یا aggregation همراه $lookup است:

sql
-- relational: two tables, one join
SELECT o.id, o.status, i.sku, i.qty, c.email
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN customers c   ON c.id = o.customer_id
WHERE o.id = 42;

سناریوی واقعی: سفارش با خط‌های embedشده و مشتری referenceشده همراه snapshot نام؛ پست وبلاگ با کامنت‌های referenceشده وقتی تعدادشان نامحدود است و پنج کامنت آخر به‌شکل preview تعبیه می‌شوند؛ کاربر با چند نشانی embedشده.

راه‌حل / روش استفاده: بر اساس الگوی دسترسی تصمیم بگیرید: چه چیز با هم خوانده می‌شود، چقدر رشد می‌کند و چند وقت یک‌بار تغییر می‌کند. واژگان عمومی طراحی در طراحی Schema، نرمال‌سازی و نوع داده و مدل سند در MongoDB در عمق آمده است. foreignField هر $lookup را index کنید.

تراکنش‌ها: session، WithTransaction و الزام replica set حیاتی ​

به زبان ساده: تراکنش (Transaction) چند نوشتن را گروه می‌کند تا یا همه انجام شوند یا هیچ‌کدام. در MongoDB یک سند از قبل اتمیک است؛ فقط وقتی تغییر چند سند یا collection را در بر می‌گیرد تراکنش لازم دارید.

بدفهمی رایج: «تراکنش روی هر MongoDB کار می‌کند.» manual آن را برای replica set و sharded cluster پشتیبانی می‌کند و مستند Laravel MongoDB صریح می‌گوید: «MongoDB standalone deployments do not support transactions.» یک mongod تنها (standalone) تراکنش را رد می‌کند (fail)؛ حتی برای توسعه آن را به‌صورت replica set تک‌گرهی اجرا کنید. دام دوم: callback داده‌شده به WithTransaction ممکن است بیشتر از یک بار اجرا شود.

تعریف: ابتدا session, err := client.StartSession()، سپس defer session.EndSession(ctx) و بعد session.WithTransaction(ctx, fn, opts...). در v2 امضای callback برابر func(ctx context.Context) (any, error) است. ctx دریافتی session را حمل می‌کند و مستند می‌گوید «the SessionContext must be used as the Context parameter for any operations that should be part of the transaction». نوع قدیمی SessionContext حذف شده و ctx معمولی همان نقش را دارد. دربارهٔ خطاهای دارای برچسب TransientTransactionError و UnknownTransactionCommitResult آمده «are retried for up to 120 seconds» و هشدار داده شده «The fn callback may be run multiple times during WithTransaction due to retry attempts, so it must be idempotent.» قاعدهٔ دیگر: «the application MUST NOT silently handle errors within the callback fn». خطا را برگردانید؛ پنهان کردنش می‌تواند driver را در retry بی‌پایان نگه دارد. گزینه‌های تراکنش: options.Transaction().SetReadConcern(readconcern.Snapshot()).SetWriteConcern(writeconcern.Majority()).

service                      session / driver                           mongod (replica set)
1  Do(ctx, begin, fn) ──────▶ StartSession
2                             WithTransaction(ctx, callback)
3                             start transaction ───────────────────────▶ snapshot opened
4                             fn(ctx): Debit(ctx) ... Credit(ctx) ─────▶ writes inside the transaction
5                             Credit fails: WriteConflict, label TransientTransactionError
6                             abort, then run fn again (attempt 2) ────▶ new snapshot
7                             commit ──────────────────────────────────▶ visible to others atomically
8  ◀──────────────────────── EndSession, return
go
// Package txn wraps Session.WithTransaction. Transactions need a replica set
// or a sharded cluster; a standalone mongod rejects them.
package txn

import (
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
	"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)

// Session is the part of *mongo.Session the helper needs.
type Session interface {
	WithTransaction(ctx context.Context, fn func(ctx context.Context) (any, error), opts ...options.Lister[options.TransactionOptions]) (any, error)
	EndSession(ctx context.Context)
}

var _ Session = (*mongo.Session)(nil)

// Begin starts a session. FromClient is the production implementation.
type Begin func() (Session, error)

// FromClient starts sessions on a real client.
func FromClient(c *mongo.Client) Begin {
	return func() (Session, error) {
		s, err := c.StartSession()
		if err != nil {
			return nil, err
		}
		return s, nil
	}
}

// Do runs fn inside a transaction. The ctx given to fn carries the session:
// every collection call inside fn must use it, or the call runs outside the
// transaction. The driver may call fn more than once (transient errors) and
// retries the commit, so fn must be safe to repeat and must not do side
// effects such as sending e-mail.
func Do(ctx context.Context, begin Begin, fn func(ctx context.Context) error) error {
	s, err := begin()
	if err != nil {
		return err
	}
	defer s.EndSession(ctx)

	opts := options.Transaction().
		SetReadConcern(readconcern.Snapshot()).
		SetWriteConcern(writeconcern.Majority())

	_, err = s.WithTransaction(ctx, func(ctx context.Context) (any, error) {
		return nil, fn(ctx)
	}, opts)
	return err
}

// ErrInsufficientFunds is a business error: it aborts the transaction and is
// not retried.
var ErrInsufficientFunds = errors.New("txn: insufficient funds")

// Ledger moves money. Both calls must receive the transaction ctx.
type Ledger interface {
	Debit(ctx context.Context, account string, cents int64) error
	Credit(ctx context.Context, account string, cents int64) error
}

// Transfer debits and credits atomically: both happen or neither does.
func Transfer(ctx context.Context, begin Begin, l Ledger, from, to string, cents int64) error {
	return Do(ctx, begin, func(ctx context.Context) error {
		if err := l.Debit(ctx, from, cents); err != nil {
			return err
		}
		return l.Credit(ctx, to, cents)
	})
}

تست‌ها session جعلی دارند که قرارداد مستند را مدل می‌کند: callback اجرا، در موفقیت commit، در خطا abort و برای برچسب TransientTransactionError اجرای دوباره. این تست کد اطراف driver است، نه تست خود driver. ثابت می‌کند انتقال هر دو طرف را commit می‌کند؛ خطای کسب‌وکار ErrInsufficientFunds بدون retry abort می‌کند و موجودی‌ها تغییر نمی‌کنند؛ خطای گذرا در credit callback را یک بار تکرار می‌کند، یعنی دو دور و دو فراخوانی debit، ولی موجودی فقط یک بار عوض می‌شود؛ و خطای شروع session بدون تغییر برمی‌گردد.

go
package txn

import (
	"context"
	"errors"
	"testing"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// memLedger stages writes and publishes them only on commit, like a
// transaction would.
type memLedger struct {
	committed map[string]int64
	staged    map[string]int64
	calls     int
	failOnce  bool
}

func newLedger() *memLedger {
	return &memLedger{committed: map[string]int64{"a": 1000, "b": 0}}
}

func (l *memLedger) begin() {
	l.staged = map[string]int64{}
	for k, v := range l.committed {
		l.staged[k] = v
	}
}

func (l *memLedger) Debit(_ context.Context, acct string, c int64) error {
	l.calls++
	if l.staged[acct] < c {
		return ErrInsufficientFunds
	}
	l.staged[acct] -= c
	return nil
}

func (l *memLedger) Credit(_ context.Context, acct string, c int64) error {
	if l.failOnce {
		l.failOnce = false
		return mongo.CommandError{Code: 112, Name: "WriteConflict", Labels: []string{"TransientTransactionError"}}
	}
	l.staged[acct] += c
	return nil
}

// fakeSession models the documented WithTransaction contract: run the callback,
// commit on success, abort on error, and re-run the whole callback when the
// error carries the TransientTransactionError label.
type fakeSession struct {
	l      *memLedger
	ended  bool
	opts   int
	rounds int
}

func (f *fakeSession) WithTransaction(ctx context.Context, fn func(context.Context) (any, error), opts ...options.Lister[options.TransactionOptions]) (any, error) {
	f.opts = len(opts)
	for {
		f.rounds++
		f.l.begin()
		res, err := fn(ctx)
		if err == nil {
			f.l.committed = f.l.staged
			return res, nil
		}
		var le mongo.LabeledError
		if errors.As(err, &le) && le.HasErrorLabel("TransientTransactionError") {
			continue
		}
		return nil, err
	}
}

func (f *fakeSession) EndSession(context.Context) { f.ended = true }

func TestTransferCommits(t *testing.T) {
	l := newLedger()
	s := &fakeSession{l: l}
	err := Transfer(context.Background(), func() (Session, error) { return s, nil }, l, "a", "b", 400)
	if err != nil {
		t.Fatal(err)
	}
	if l.committed["a"] != 600 || l.committed["b"] != 400 {
		t.Fatalf("balances %v", l.committed)
	}
	if !s.ended || s.opts != 1 {
		t.Fatalf("session ended=%v opts=%d", s.ended, s.opts)
	}
}

func TestBusinessErrorAbortsWithoutRetry(t *testing.T) {
	l := newLedger()
	s := &fakeSession{l: l}
	err := Transfer(context.Background(), func() (Session, error) { return s, nil }, l, "a", "b", 5000)
	if !errors.Is(err, ErrInsufficientFunds) {
		t.Fatalf("got %v", err)
	}
	if s.rounds != 1 {
		t.Fatalf("a business error must not be retried, rounds=%d", s.rounds)
	}
	if l.committed["a"] != 1000 || l.committed["b"] != 0 {
		t.Fatalf("nothing may be committed: %v", l.committed)
	}
}

// The callback runs twice, yet the balances change once: the aborted first
// attempt left nothing behind. A side effect outside the transaction would
// have run twice, which is the rule the doc comment on Do states.
func TestTransientErrorReRunsCallbackOnce(t *testing.T) {
	l := newLedger()
	l.failOnce = true
	s := &fakeSession{l: l}
	if err := Transfer(context.Background(), func() (Session, error) { return s, nil }, l, "a", "b", 400); err != nil {
		t.Fatal(err)
	}
	if s.rounds != 2 || l.calls != 2 {
		t.Fatalf("rounds=%d debit calls=%d, want 2 and 2", s.rounds, l.calls)
	}
	if l.committed["a"] != 600 || l.committed["b"] != 400 {
		t.Fatalf("balances %v", l.committed)
	}
}

func TestBeginErrorIsReturned(t *testing.T) {
	boom := errors.New("no session")
	err := Do(context.Background(), func() (Session, error) { return nil, boom }, func(context.Context) error { return nil })
	if !errors.Is(err, boom) {
		t.Fatalf("got %v", err)
	}
}
Session.WithTransaction: the callback may run more than onceStartSessionrun callback fnctx carries the sessioncommitEndSession, returnnilabort transactionon any errorTransientTransactionError?yes: retry up to 120 sno: return the error1 Every collection call inside fn must use the ctx passed to fn, or it runs outside the transaction.2 Never swallow an error inside fn: return it, or the driver cannot tell the transaction was aborted.3 No e-mail, HTTP call or counter increment in fn: a retry repeats it.
پرسشپاسخ
کدام استقرارها؟طبق manual، replica set با feature compatibility version حداقل 4.0 و sharded cluster حداقل 4.2
mongod مستقل؟نه
تراکنش تودرتو؟نه؛ بستهٔ Laravel یک RuntimeException می‌دهد
پنجرهٔ retry پیش‌فرض WithTransaction؟120 ثانیه؛ withTransactionTimeout در سورس driver
ctx خود callback مهم است؟بله؛ استفاده از ctx دیگر یعنی اجرای عملیات بیرون تراکنش
اثر جانبی در callback؟نه؛ retry آن را تکرار می‌کند

سناریوی واقعی: انتقال پول بین دو سند حساب؛ ساخت سفارش و کاهش موجودی در دو collection؛ جابه‌جایی سند بین collectionها.

راه‌حل / روش استفاده: ابتدا ببینید می‌توانید تغییر را داخل یک سند مدل کنید تا تراکنش نخواهید. اگر لازم شد، در service آغازش کنید، ctx را به همهٔ فراخوانی‌های repository بدهید و کوتاه نگهش دارید. ایمیل و انتشار در صف را بعد از commit یا از طریق outbox انجام دهید؛ الگوی Outbox. برای توسعه replica set تک‌گرهی کافی است.

تضمین خواندن و نوشتن: Read و write concern مهم ​

به زبان ساده: تضمین نوشتن (Write concern) می‌گوید چند سرور باید نوشتن را تأیید کنند تا «ok» بگیرید. تضمین خواندن (Read concern) می‌گوید دادهٔ خوانده‌شده چقدر امن باشد: ممکن است rollback شود یا اکثریت آن را تأیید کرده باشند.

بدفهمی رایج: «نوشتن تأییدشده پایدار است.» تأیید به write concern بستگی دارد. با w: 1 فقط primary آن را دارد؛ اگر پیش از replication خراب شود، نوشتن می‌تواند rollback شود. با majority از failover جان سالم به در می‌برد. concern تأخیر هزینه دارد؛ تضمین قوی‌تر انتظار بیشتر می‌خواهد.

تعریف: بستهٔ go.mongodb.org/mongo-driver/v2/mongo/writeconcern تابع‌های Majority()، W1()، Journaled()، Unacknowledged() و Custom(tag) را دارد؛ .../readconcern هم Local()، Available()، Majority()، Linearizable() و Snapshot() را می‌دهد. آن‌ها را روی client با SetWriteConcern و SetReadConcern، روی database یا collection، یا برای هر تراکنش تنظیم می‌کنید. ترجیح خواندن (Read preference) با readpref.Primary()، Secondary() و مانند آن عضو پاسخ‌دهنده را انتخاب می‌کند.

Concernتضمینهزینهکاربرد
write w: 1primary اعمال کرده استکمترینlog و metric
write majorityاکثریت دارند؛ از failover عبور می‌کندیک رفت‌وبرگشت replicationپول، سفارش و هر دادهٔ ازدست‌نرفتنی
write journaledدر journal روی دیسک نوشته شدههمگام‌سازی دیسکپایداری بیشتر روی یک گره
read localآخرین دادهٔ گره، با احتمال rollbackکمترینبیشتر خواندن‌ها
read majorityدادهٔ تأییدشدهٔ اکثریتشاید کمی عقب باشدایمنی خواندن پس از failover
read snapshotنمای سازگار از یک لحظهدر تراکنش استفاده می‌شودخواندن چندسندی
read linearizableهمهٔ نوشتن‌های majority پیشین را منعکس می‌کندکندترین، فقط primaryخواندن سخت‌گیرانهٔ نادر

سناریوی واقعی: سفارش با majority نوشته می‌شود، ولی صفحهٔ آن با local از secondary خوانده می‌شود و چند صد میلی‌ثانیه کهنه است؛ برای کاتالوگ قابل قبول است، برای «سفارشم همین الان ثبت شد» نه. نمونهٔ دیگر تراکنش با خواندن snapshot و نوشتن majority است. زمینهٔ replication در Replication، Read Replica و Failover آمده است.

راه‌حل / روش استفاده: پیش‌فرض امن را روی client بگذارید، یعنی نوشتن majority. برای دادهٔ قابل از دست دادن آن را در سطح collection ضعیف کنید و نوشتن خودتان را از primary بخوانید.

جریان تغییرات و GridFS مهم ​

به زبان ساده: جریان تغییرات (Change stream) خوراک زندهٔ insert، update و delete در collection، database یا cluster است. GridFS فایل بزرگ‌تر از سند را تکه‌تکه ذخیره می‌کند.

بدفهمی رایج: «change stream صف است.» دنبالهٔ oplog است؛ برای ادامه بعد از restart باید خودتان resume token را پایدار ذخیره کنید. فاصلهٔ بیشتر از پنجرهٔ oplog قابل resume نیست و مثل تراکنش replica set یا sharded cluster لازم دارد. دربارهٔ GridFS هم «فایل 100 MB را داخل یک فیلد می‌گذارم» غلط است؛ سقف سند 16 MiB است.

تعریف: coll.Watch(ctx, pipeline, options.ChangeStream().SetFullDocument(options.UpdateLookup).SetResumeAfter(token)) یک *mongo.ChangeStream می‌دهد که Next، Decode، Err، ResumeToken و Close دارد. pipeline می‌تواند روی operationType یک $match بگذارد تا فیلتر روی سرور انجام شود. Follow در نمونه هر رویداد را داخل Event decode می‌کند، آخرین resume token را می‌دهد و stream را با context جداشده می‌بندد تا cleanup پس از لغو هم انجام شود. تست‌ها سند pipeline و decode رویداد را پوشش می‌دهند؛ خود stream سرور لازم دارد و «انتظار می‌رود؛ اجرا نشده» است. راهنمای GridFS در mongodb.com/docs/manual/core/gridfs/ دو collection به نام fs.files و fs.chunks را توضیح می‌دهد. driver هم bucket := db.GridFSBucket() و UploadFromStream و DownloadToStream را دارد؛ سورس mongo/gridfs_bucket.go را ببینید. در سیستم واقعی بیشتر تیم‌ها بایت فایل بزرگ را در object storage و URL آن را در سند نگه می‌دارند؛ موضوع بارگذاری فایل، S3 و CDN.

go
// Package changes tails a collection with a change stream. Change streams need
// a replica set or sharded cluster, like transactions.
package changes

import (
	"context"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// Event is the part of a change event the application reads.
type Event struct {
	OperationType string `bson:"operationType"`
	DocumentKey   struct {
		ID bson.ObjectID `bson:"_id"`
	} `bson:"documentKey"`
	FullDocument bson.Raw `bson:"fullDocument,omitempty"`
}

// Pipeline keeps only the listed operation types, filtered on the server.
func Pipeline(ops ...string) mongo.Pipeline {
	return mongo.Pipeline{{{Key: "$match", Value: bson.D{
		{Key: "operationType", Value: bson.D{{Key: "$in", Value: ops}}},
	}}}}
}

// Follow reads events until ctx ends or the stream fails. It returns the last
// resume token so the caller can persist it and continue after a restart:
// pass it back as resume (nil starts from now).
func Follow(ctx context.Context, c *mongo.Collection, resume bson.Raw, handle func(Event) error) (bson.Raw, error) {
	opts := options.ChangeStream().SetFullDocument(options.UpdateLookup)
	if resume != nil {
		opts.SetResumeAfter(resume)
	}
	cs, err := c.Watch(ctx, Pipeline("insert", "update", "replace", "delete"), opts)
	if err != nil {
		return resume, err
	}
	defer cs.Close(context.WithoutCancel(ctx))

	token := resume
	for cs.Next(ctx) {
		var ev Event
		if err := cs.Decode(&ev); err != nil {
			return token, err
		}
		if err := handle(ev); err != nil {
			return token, err
		}
		token = cs.ResumeToken()
	}
	return token, cs.Err()
}
go
package changes

import (
	"testing"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func TestPipeline(t *testing.T) {
	b, err := bson.MarshalExtJSON(bson.M{"p": Pipeline("insert", "delete")}, false, false)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"p":[{"$match":{"operationType":{"$in":["insert","delete"]}}}]}`
	if string(b) != want {
		t.Fatalf("got %s", b)
	}
}

func TestDecodeEvent(t *testing.T) {
	id := bson.NewObjectID()
	raw, err := bson.Marshal(bson.D{
		{Key: "operationType", Value: "update"},
		{Key: "documentKey", Value: bson.D{{Key: "_id", Value: id}}},
		{Key: "fullDocument", Value: bson.D{{Key: "email", Value: "a@example.test"}}},
	})
	if err != nil {
		t.Fatal(err)
	}
	var ev Event
	if err := bson.Unmarshal(raw, &ev); err != nil {
		t.Fatal(err)
	}
	if ev.OperationType != "update" || ev.DocumentKey.ID != id {
		t.Fatalf("event %+v", ev)
	}
	if ev.FullDocument.Lookup("email").StringValue() != "a@example.test" {
		t.Fatal("full document missing")
	}
}
app                                   mongod
1  Watch(ctx, $match insert/update) ─▶ open stream at "now" (or after the resume token)
2                                      ... a write happens somewhere ...
3  Next → true ◀───────────────────── event { operationType, documentKey, fullDocument, _id: <token> }
4  handle(event); save ResumeToken to a durable store
5  process restarts: Watch(..., SetResumeAfter(saved token)) ─▶ continues after the last handled event

سناریوی واقعی: بی‌اعتبار کردن cache بعد از تغییر محصول، فرستادن تغییر وضعیت سفارش به websocket، تغذیهٔ index جست‌وجو و ثبت audit. برای رویداد بین سرویس‌ها طرح مقاوم‌تر outbox است؛ الگوی Outbox و موضوع broker در Go رویدادمحور.

راه‌حل / روش استفاده: token را بعد از پردازش هر رویداد پایدار کنید. تحویل حداقل یک‌بار (At-least-once) است، پس handler باید idempotent باشد. match را روی سرور انجام دهید و خطای «resume token not found» را با همگام‌سازی کامل مدیریت کنید.

مدیریت خطا: ErrNoDocuments، duplicate key 11000 و timeout حیاتی ​

به زبان ساده: driver خطاهای گوناگون می‌دهد. کد شما چند نوع را تشخیص می‌دهد و به زبان خودش تبدیل می‌کند: پیدا نشد، تعارض، timeout و در دسترس نیست.

بدفهمی رایج: «err.Error() را با string مقایسه کن» یا «به mongo.WriteException type assertion بزن». stringها بین نسخه‌های سرور عوض می‌شوند و کلید تکراری (Duplicate key) ممکن است در WriteException، BulkWriteException یا CommandError برسد. helperها را به کار بگیرید: mongo.IsDuplicateKeyError(err) که «returns true if err is a duplicate key error» و برای خطای bulk «if at least one of the errors is a duplicate key error»؛ همچنین mongo.IsTimeout(err)، mongo.IsNetworkError(err) و errors.Is(err, mongo.ErrNoDocuments).

تعریف: helper کدهای 11000 با نام DuplicateKey، 11001، 12582 و 16460 با شرط متن پیام را بررسی می‌کند. فهرست کدهای manual مقدار 11000 را DuplicateKey می‌نامد. خطاهای سرور mongo.ServerError را با HasErrorCode(code)، HasErrorLabel(label) و ErrorCodes() پیاده می‌کنند.

خطابررسیمعنای دامنهHTTP
mongo.ErrNoDocumentserrors.Isپیدا نشد404
duplicate key، کد 11000mongo.IsDuplicateKeyErrorتعارض409
پایان deadlinemongo.IsTimeout یا errors.Is(err, context.DeadlineExceeded)timeout؛ نتیجهٔ نوشتن نامعلوم504
لغو توسط clienterrors.Is(err, context.Canceled)صدازننده رفته استندارد؛ log در سطح info
شبکه یا انتخاب سرورmongo.IsNetworkError و متن خطای server selectionدر دسترس نیست503
شکست اعتبارسنجی سند، کد 121HasErrorCode(121)ورودی نامعتبری که از بررسی Go گذشته422 یا 500
برچسب TransientTransactionErrorHasErrorLabelتکرار کل تراکنشWithTransaction رسیدگی می‌کند

سناریوی واقعی: handler ثبت‌نام بدون lookup قبلی برای email گرفته‌شده 409 می‌دهد؛ endpoint خواندن برای id غایب 404 می‌دهد؛ timeout به 504 و metric تبدیل می‌شود.

راه‌حل / روش استفاده: در یک جا نگاشت کنید؛ mapErr در repository. با %w wrap کنید تا جزئیات driver در log بماند و handler فقط خطای دامنه را مقایسه کند؛ Errors، Panic، Recover و Defer.

اعتبارسنجی Schema با $jsonSchema مهم ​

به زبان ساده: اعتبارسنجی (Validation) در MongoDB یعنی به collection قاعده بدهید، مثلاً «email رشته و created_at تاریخ باشد»، تا سرور سند ناقض را رد کند؛ حتی اگر از باگ، اسکریپت یا سرویس دیگر آمده باشد.

بدفهمی رایج: «validation جای بررسی Go را می‌گیرد.» آخرین خط دفاع است، نه اولین؛ خطای خروجی کد سرور 121 است، نه پیام دوستانه. اضافه کردن validator هم خودبه‌خود سندهای قدیمی را بررسی نمی‌کند مگر درخواست کنید؛ با validationLevel: "moderate" سند نامعتبر موجود در updateهایی که سراغش نمی‌روند دست‌نخورده می‌ماند.

تعریف: $jsonSchema عملگر query برای تطبیق با زیرمجموعهٔ JSON Schema است، شامل bsonType، required، properties، pattern و minimum. هنگام ساخت collection آن را با options.CreateCollection().SetValidator(...).SetValidationLevel("strict").SetValidationAction("error") تنظیم کنید، یا بعداً فرمان collMod را با db.RunCommand بفرستید. validationAction: "warn" به‌جای رد کردن log می‌کند؛ برای دورهٔ پاک‌سازی دادهٔ قدیمی مفید است.

go
// Package schema builds a $jsonSchema validator so the database refuses
// documents that break the shape the Go structs assume.
package schema

import (
	"context"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// Users returns the validator document for the users collection.
func Users() bson.D {
	return bson.D{{Key: "$jsonSchema", Value: bson.D{
		{Key: "bsonType", Value: "object"},
		{Key: "required", Value: bson.A{"email", "name", "created_at"}},
		{Key: "properties", Value: bson.D{
			{Key: "email", Value: bson.D{
				{Key: "bsonType", Value: "string"},
				{Key: "pattern", Value: `^[^@\s]+@[^@\s]+$`},
			}},
			{Key: "name", Value: bson.D{{Key: "bsonType", Value: "string"}, {Key: "minLength", Value: 1}}},
			{Key: "age", Value: bson.D{{Key: "bsonType", Value: "int"}, {Key: "minimum", Value: 0}}},
			{Key: "created_at", Value: bson.D{{Key: "bsonType", Value: "date"}}},
		}},
	}}}
}

// Create makes the collection with the validator. validationAction "error"
// rejects bad writes; "warn" only logs them (useful while migrating).
func Create(ctx context.Context, db *mongo.Database, name string) error {
	return db.CreateCollection(ctx, name, options.CreateCollection().
		SetValidator(Users()).
		SetValidationLevel("strict").
		SetValidationAction("error"))
}

// Modify changes the validator of an existing collection with collMod.
func Modify(ctx context.Context, db *mongo.Database, name string) error {
	cmd := bson.D{
		{Key: "collMod", Value: name},
		{Key: "validator", Value: Users()},
		{Key: "validationLevel", Value: "moderate"},
	}
	return db.RunCommand(ctx, cmd).Err()
}

تست‌ها شکل validator را بررسی می‌کنند: آرایهٔ $jsonSchema.required سه فیلد دارد، pattern مربوط به email موجود است و فیلدهای اجباری با کلیدهای struct تطبیق دارند. تست models نکتهٔ مرتبطی را هم تثبیت می‌کند: bsonType: "int" یعنی BSON int32 و "long" یعنی int64. یک int در Go اگر جا شود int32 نوشته می‌شود، ولی مقدار int64 به‌شکل int64 ذخیره می‌شود. پس نوع schema را با توجه به نوع Go انتخاب کنید.

go
package schema

import (
	"reflect"
	"strings"
	"testing"

	"go.mongodb.org/mongo-driver/v2/bson"

	"academy/mongodb-with-go/models"
)

func TestValidatorShape(t *testing.T) {
	raw, err := bson.Marshal(Users())
	if err != nil {
		t.Fatal(err)
	}
	r := bson.Raw(raw)
	req, err := r.LookupErr("$jsonSchema", "required")
	if err != nil {
		t.Fatal(err)
	}
	arr, ok := req.ArrayOK()
	if !ok {
		t.Fatal("required must be an array")
	}
	vals, _ := arr.Values()
	if len(vals) != 3 {
		t.Fatalf("expected 3 required fields, got %d", len(vals))
	}
	if _, err := r.LookupErr("$jsonSchema", "properties", "email", "pattern"); err != nil {
		t.Fatal("email pattern missing")
	}
}

// bsonKeys returns the document keys of a struct, from its bson tags, with
// inline structs flattened. Fields tagged "-" and omitempty fields are listed
// separately because omitempty fields cannot be "required".
func bsonKeys(t reflect.Type) (always, optional []string) {
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		tag := f.Tag.Get("bson")
		if tag == "-" || !f.IsExported() {
			continue
		}
		parts := strings.Split(tag, ",")
		name := parts[0]
		inline, omit := false, false
		for _, o := range parts[1:] {
			inline = inline || o == "inline"
			omit = omit || o == "omitempty"
		}
		if inline {
			a, o := bsonKeys(f.Type)
			always, optional = append(always, a...), append(optional, o...)
			continue
		}
		if name == "" {
			name = strings.ToLower(f.Name)
		}
		if omit {
			optional = append(optional, name)
		} else {
			always = append(always, name)
		}
	}
	return
}

// Every field the validator requires must be a key the model always writes,
// and every property it describes must be a key of the model. Renaming a tag
// in models.User fails this test.
func TestValidatorMatchesModelTags(t *testing.T) {
	always, optional := bsonKeys(reflect.TypeOf(models.User{}))
	all := map[string]bool{}
	for _, k := range append(append([]string{}, always...), optional...) {
		all[k] = true
	}
	alwaysSet := map[string]bool{}
	for _, k := range always {
		alwaysSet[k] = true
	}
	raw, _ := bson.Marshal(Users())
	r := bson.Raw(raw)
	req, _ := r.Lookup("$jsonSchema", "required").Array().Values()
	for _, e := range req {
		if !alwaysSet[e.StringValue()] {
			t.Errorf("required field %q is not an always-written key of models.User (keys: %v)", e.StringValue(), always)
		}
	}
	props, _ := r.Lookup("$jsonSchema", "properties").Document().Elements()
	for _, p := range props {
		if !all[p.Key()] {
			t.Errorf("property %q is not a key of models.User", p.Key())
		}
	}
}

سناریوی واقعی: دیتابیس مشترک که چند سرویس در users می‌نویسند؛ migrationی که قواعد را ابتدا در حالت warn سخت‌تر و بعد به error تبدیل می‌کند.

راه‌حل / روش استفاده: validator را در کد کنار struct نگه دارید، در شروع یا job مهاجرت اعمال کنید و در مجموعهٔ تست یکپارچه با سرور واقعی آزمایش کنید.

تست: mongod واقعی یا testcontainers؛ interface و repository جعلی حیاتی ​

به زبان ساده: بیشتر منطق اطراف دیتابیس را بدون دیتابیس می‌توان تست کرد. برای باقی موارد mongod واقعی اجرا کنید.

بدفهمی رایج: «برای تست MongoDB درون‌حافظه‌ای داریم.» driver هیچ mock درون‌حافظه‌ای از سرور ندارد. helper تست یکپارچهٔ خود driver، یعنی mtest، در v2 زیر مسیر internal، یعنی internal/integration/mtest است؛ کد برنامه نمی‌تواند آن را import کند. انتخاب شما interface با بدل جعلی (Fake)، یا mongod واقعی است؛ محلی یا ساخته‌شده در هر اجرای تست با testcontainers.

تعریف: سه لایه داریم. تست واحد (Unit test) خالص: فیلتر، update و pipeline را با bson.MarshalExtJSON marshal و رشته‌ها را مقایسه کنید؛ مدل‌ها را marshal و unmarshal کنید. تست متکی به fake: رابط Collection repository را با fake پیاده کنید که نتیجه را از mongo.NewCursorFromDocuments و mongo.NewSingleResultFromDocument می‌سازد؛ این سازنده‌ها برای همین هدف در driver هستند. تست یکپارچه (Integration test): سرور واقعی برای چیزی که فقط سرور ثابت می‌کند؛ unique index، TTL، تراکنش، $lookup و change stream. کتابخانهٔ testcontainers در Go ماژول MongoDB با نشانی golang.testcontainers.org/modules/mongodb/ دارد که container اجرای تست را شروع می‌کند. آن را پشت build tag یا بررسی -short بگذارید تا تست‌های واحد سریع بمانند. برای این فصل اجرا نشده؛ Docker در دسترس نبود.

مورد تستسرور می‌خواهد؟روش
سند فیلتر، update و pipelineنهbson.MarshalExtJSON و مقایسهٔ رشته
tagهای struct و رفت‌وبرگشتنهbson.Marshal، bson.Unmarshal
منطق repository و نگاشت خطانهCollection جعلی
منطق callback تراکنشنهsession جعلی
unique index، TTL و $jsonSchemaبلهmongod واقعی
تراکنش و change streamبله، به‌شکل replica setmongod --replSet واقعی یا container
رفتار شکست اتصالنهport بسته با server selection timeout کوتاه؛ تست نمونه

سناریوی واقعی: مرحلهٔ unit در CI تست‌های سریع را ظرف چند ثانیه اجرا می‌کند؛ job شبانه container بالا می‌آورد و go test -tags integration را اجرا می‌کند.

راه‌حل / روش استفاده: به interfaceهای کوچک وابسته باشید، fake را با سازنده‌های driver بسازید و تست‌های یکپارچه را کم و متمرکز نگه دارید؛ Testing و Benchmarking و Mocking با Interface.

سازوکار (Mechanics) ​

داخل یک فراخوانی چه می‌گذرد مهم ​

به زبان ساده: فراخوانی collection این مسیر را دارد: تبدیل مقدار Go به BSON، انتخاب سرور، ارسال فرمان روی اتصال pool، انتظار پاسخ و تبدیل نتیجه به نوع Go.

بدفهمی رایج: «هر فراخوانی یک اتصال باز می‌کند.» client برای هر سرور مخزن اتصال (Connection pool) دارد. فراخوانی اتصال را تحویل می‌گیرد، استفاده می‌کند و پس می‌دهد. وقتی همهٔ اتصال‌های MaxPoolSize مشغول باشند، فراخوانی بعد منتظر می‌ماند؛ مستند می‌گوید «requests to a server will block if this maximum is reached».

تعریف: مرحله‌ها و تنظیمی که هر مرحله را محدود می‌کند:

1  marshal filter/update/document  → BSON bytes (errors: unsupported type, bad tag)
2  select a server                 → bounded by ServerSelectionTimeout (default 30 s) and your ctx
3  check out a pooled connection   → waits when the pool is at MaxPoolSize (default 100)
4  send the command, wait          → bounded by the ctx deadline, or the client Timeout if the ctx has none
5  read the reply or first batch   → cursor commands return a batch and a cursor id
6  unmarshal into your type        → Decode errors: type mismatch, e.g. a string into an int field
7  connection returns to the pool
مرحلهتنظیمشکل شکست
2، انتخاب سرورSetServerSelectionTimeout، readprefserver selection error: context deadline exceeded
3، poolSetMaxPoolSize، SetMinPoolSize، SetMaxConnIdleTimeزیر بار فراخوانی کند می‌شود، در حالی که CPU برنامه بیکار است
4، اجراdeadline روی ctx و SetTimeoutcontext deadline exceeded و mongo.IsTimeout(err) == true
5، cursorSetBatchSize، NoCursorTimeoutپس از بستن cursor بیکار توسط سرور، CursorNotFound
6، decodeنوع‌ها و tagهای structخطایی شبیه cannot decode string into an integer type

نام‌ها و مسیرهای دقیق import حیاتی ​

موردنام دقیق
ماژولgo.mongodb.org/mongo-driver/v2
بسته‌ها.../v2/mongo، .../v2/bson، .../v2/mongo/options، .../v2/mongo/readpref، .../v2/mongo/readconcern، .../v2/mongo/writeconcern
اتصالmongo.Connect(opts ...*options.ClientOptions) (*mongo.Client, error)
گزینه‌هاoptions.Client().ApplyURI(uri).SetMaxPoolSize(n)...
نوع شناسهbson.ObjectID، bson.NewObjectID()، bson.ObjectIDFromHex(s)
سند مرتبbson.D با عضو bson.E{Key, Value}
Pipelinemongo.Pipeline از نوع []bson.D
خطای نشانه (Sentinel error)mongo.ErrNoDocuments
تابع‌های کمکیmongo.IsDuplicateKeyError، mongo.IsTimeout، mongo.IsNetworkError
کمک‌تابع تستmongo.NewCursorFromDocuments، mongo.NewSingleResultFromDocument
تراکنشclient.StartSession()، session.WithTransaction(ctx, fn, opts...)، session.EndSession(ctx)
جریان تغییراتcoll.Watch(ctx, pipeline, opts...)

مقدار دقیق خطاها و محدودیت‌ها مهم ​

مقدارمعنامنبع
mongo: no documents in resultمتن mongo.ErrNoDocumentsسورس driver، single_result.go
11000 DuplicateKeyنقض unique indexکدهای خطای manual
11001، 12582، 16460 همراه " E11000 " در پیامشکل‌های دیگر duplicate key که IsDuplicateKeyError می‌پذیردسورس driver، errors.go
121 DocumentValidationFailurevalidator مجموعه سند را رد کردهکدهای خطای manual
85 IndexOptionsConflict، 86 IndexKeySpecsConflictنام index یکسان، تعریف متفاوتنام خطاهای سرور
16 MiBبیشترین اندازهٔ یک سندmanual: "Documents in MongoDB must be smaller than 16 mebibytes"
120 sمدت retry تراکنش گذرا در WithTransactionسورس driver، session.go
100پیش‌فرض MaxPoolSizeسورس driver، clientoptions.go
30 sپیش‌فرض timeout انتخاب سرورسورس driver، clientoptions.go
حدود 60 sفاصلهٔ اجرای کار پس‌زمینهٔ TTLصفحهٔ TTL در manual

حل مسئله‌های کلاسیک ​

باگنشانهراه‌حلهزینه
کپی JSON درخواست در فیلتر{"password":{"$ne":""}} همه را تطبیق می‌دهدورودی تایپ‌دار builder و فیلد string در struct درخواستچند تابع builder
bson.M برای sort، hint یا کلید indexdriver برای sort یا hint چندکلیدی ErrMapForOrderedArgument می‌دهد؛ کلید index باید مرتب باشدbson.Dندارد
cursor بدون Closeانباشته شدن cursor در سرورdefer cur.Close(ctx) یا Allندارد
نادیده گرفتن cur.Err()قطع بی‌صدای نتیجهبررسی پس از حلقهٔ Nextیک خط
تلقی‌کردن «نتیجه‌ای پیدا نشد» در FindOne به‌عنوان موفقیتاستفاده از struct صفر انگار بارگذاری شدهerrors.Is(err, mongo.ErrNoDocuments)یک شاخه
race در بررسی‌سپس‌درجدو حساب با یک emailunique index و نگاشت کد 11000یک index
خواندن‌تغییر‌نوشتنlost updateعملگر $inc/$set و شرط محافظ در فیلترفکر کردن بر حسب operator
صفحهٔ دور با skipکندتر شدن صفحه‌هاrange pagination روی _idحذف دسترسی تصادفی به صفحه
نبود indexquery کند، CPU بالا، COLLSCAN در explaincompound index با ترتیب ESRسربار نوشتن
آرایهٔ تعبیه‌شدهٔ نامحدودخطای 16 MiB و update کندانتقال فرزندها به collection خودشانارجاع و query
Connect بدون Pingشکست اولین درخواست بعد از 30 sPing با timeout کوتاه در شروعچند ms
client به‌ازای درخواستاتصال زیاد و درخواست کندیک client در mainاتصال وابستگی‌ها
تراکنش روی سرور standaloneخطا در اولین تراکنشreplica set تک‌گرهی برای توسعهراه‌اندازی
اثر جانبی داخل callback تراکنشایمیل تکراری بعد از retryپس از commit یا outboxیک الگو
پنهان کردن خطا در callbackretry تا پایان پنجره ادامه داردبرگرداندن همهٔ خطاهاانضباط
omitempty روی عددی که صفر واقعی داردصفر هیچ‌وقت ذخیره نمی‌شودنوع pointer یا حذف omitemptyتغییر نوع

قواعد تلاش مجدد (Retry) مهم ​

خطاRetry؟روش
TransientTransactionErrorبلهWithTransaction از قبل انجام می‌دهد، تا 120 s
UnknownTransactionCommitResultبلهWithTransaction، commit را تکرار می‌کند
خطای انتخاب سروربا backoffdriver از قبل یک بار retry کرده؛ retryable read و write پیش‌فرض true دارند؛ retryable write فقط روی replica set یا sharded cluster است؛ SetRetryWrites را ببینید
mongo.IsTimeout روی خواندنشایدفقط اگر بودجهٔ کل باقی است
mongo.IsTimeout روی نوشتنفقط اگر idempotent استبازخوانی یا کلید طبیعی / idempotency key
duplicate key، کد 11000نهتبدیل به تعارض؛ برای race در upsert یک بار به‌شکل update تکرار کنید
ErrNoDocumentsنهپیدا نشد

انتخاب (Choosing) ​

موقعیتانتخابتکنیک اضافهدلیل
جست‌وجو با کلید یکتاFindOne با unique indexنگاشت ErrNoDocumentsیک جست‌وجو در index
فهرست feed یا collection در APIFind با range pagination روی _idlimit + 1 برای وجود صفحهٔ بعدهزینهٔ ثابت هر صفحه
جدول back-office با شمارهٔ صفحهlimit + skipسقف شمارهٔ صفحهدر اندازهٔ کوچک سادگی مهم‌تر است
شمارنده، موجودی پول یا کالاUpdateOne + $inc با شرط در فیلتربررسی MatchedCountاتمیک روی یک سند
ساخت یا تغییر با کلید طبیعیupsert + unique index$setOnInsert و یک retry برای 11000بدون race، یک رفت‌وبرگشت
import یا sync سطرهای زیادBulkWrite unorderedدسته‌های حدود هزار‌تاییرفت‌وبرگشت بسیار کمتر از فراخوانی برای هر سطر
دادهٔ مرتبط، محدود و خوانده‌شده با همembedفیلدهای snapshotیک خواندن و یک نوشتن اتمیک
دادهٔ مرتبط مشترک، بزرگ یا پرتغییرreference$lookup و index روی فیلد خارجیبدون تکرار داده
گزارش روی collectionaggregation با $match در ابتداپیش‌تجمیع اگر سنگین استانجام کار روی سرور
تغییر چندسندیWithTransactioncallback idempotent و outbox برای اثر جانبیاتمیک بودن بین سندها
نوشتن چند سرویس در یک collectionvalidator با $jsonSchemaاول warn، سپس errorتحمیل شکل توسط دیتابیس
واکنش به تغییرchange streamresume token پایداربدون polling
فایل خیلی بزرگobject storage یا در صورت الزام MongoDB، GridFSURL یا id فایل در سندسقف 16 MiB
تست واحدinterface + fakeسازندهٔ cursor خود driverسریع و بی‌نیاز از سرور
رفتار index و تراکنشmongod واقعی یا testcontainersتست یکپارچه با tagفقط سرور آن را نشان می‌دهد

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

مونولیت (Monolith): یک پردازه، یک دیتابیس ​

یک binary و یک *mongo.Client که در main ساخته و با Ping بررسی می‌شود و موقع خاموشی در تابع deferشده بسته می‌شود؛ پردازه‌ها، Signal و خاموشی مرتب. repositoryها handleهای *mongo.Collection را که یک‌بار ساخته شده‌اند نگه می‌دارند. handler یک service می‌گیرد که به interface کوچک وابسته است. indexها هنگام شروع از یک فهرست در بستهٔ indexes ساخته می‌شوند. مثال: فروشگاهی با سه collection به نام users، orders و sessions. سند orders خط‌هایش را embed می‌کند، sessions دارای TTL index است و POST /orders یک سند می‌نویسد؛ تراکنش لازم نیست.

مونولیت ماژولار و چند دیتابیس ​

در مونولیت ماژولار (Modular monolith)، هر ماژول مالک collectionهای خودش است و تابع ارائه می‌دهد، نه handle collection. ماژول billing مستقیم orders را نمی‌خواند؛ از ماژول سفارش می‌پرسد. هماهنگی چند دیتابیس، مثلاً PostgreSQL برای پول و MongoDB برای کاتالوگ و session، بر عهدهٔ برنامه است. هیچ‌چیز commit در PostgreSQL و نوشتن در MongoDB را اتمیک نمی‌کند. ترتیب نوشتن را طوری بچینید که crash وضعیت بازیابی‌پذیر بگذارد؛ اول رکورد پایدار را بنویسید، یا outbox به کار ببرید؛ الگوی Outbox. همتای SQL این repository در database/sql و pgx و لایهٔ HTTP مصرف‌کننده‌اش در ساخت REST API در Go است.

میکروسرویس‌ها (Microservices) ​

قاعدهٔ اول: collection متعلق به یک سرویس است. بقیه داده را از API یا رویداد می‌گیرند، نه با اتصال به دیتابیس آن. change stream می‌تواند سرویس index یا بی‌اعتبارسازی cache را تغذیه کند؛ روش مقاوم انتشار رویداد دامنه این است که رویداد را در collection مربوط به outbox، داخل همان تراکنش تغییر وضعیت بنویسید و relay منتشرش کند. جریان نمونه: سرویس orders در یک WithTransaction روی orders و outbox می‌نویسد؛ relay با change stream و resume token پایدار دنبالهٔ outbox را می‌خواند و به broker می‌فرستد؛ inventory بر اساس id رویداد idempotent مصرف می‌کند. unique index روی processed_events.event_id است و کد 11000 یعنی «قبلاً پردازش شده». سازگاری بین سرویس‌ها نهایی (Eventual consistency) است: saga و idempotency key، نه تراکنش توزیع‌شده؛ مصرف‌کنندهٔ Idempotent و Inbox.

دادهٔ توزیع‌شده: replica، cache، sharded cluster و چند منطقه ​

MongoDB عملیاتی یک مجموعهٔ replica یا Replica set است: primary نوشتن می‌گیرد و secondaryها تکثیر می‌کنند. خواندن از secondary با readpref.Secondary می‌تواند کهنه باشد؛ write concern برابر majority جلوی rollback هنگام failover را می‌گیرد. driver خودش primary تازه را با انتخاب سرور و retryable write پیدا می‌کند؛ پس failover به‌شکل چند فراخوانی کند دیده می‌شود و برای نوشتن غیرidempotent با نتیجهٔ نامعلوم، timeout مبهم هم دارد. cache جلوی دیتابیس، مثلاً Redis، خواندن را به hit تبدیل می‌کند و مسئلهٔ invalidation می‌آورد؛ change stream سیگنال خوبی برای آن است. sharded cluster یک collection را با shard key تقسیم می‌کند. query دارای shard key به یک shard می‌رود و بقیه روی همه پخش می‌شوند؛ تراکنش میان shardها کندتر است. پیش از نیاز، shard key را انتخاب کنید. ایده‌های عمومی در Partitioning و Sharding و رفتار خاص MongoDB در MongoDB در عمق آمده است.

مسیر مقیاس‌پذیری: 1×، 10×، 100× ​

بارچه عوض می‌شودروش کار
1×، یک instance و یک mongodاشتباه‌ها دیده نمی‌شوندیک client، Ping، unique index، فیلتر تایپ‌دار و تست با fake
10×، چند instance برنامه و replica setحاصل‌ضرب اندازهٔ pool در تعداد instance به سقف اتصال سرور می‌رسد؛ query کند آشکار می‌شودتنظیم MaxPoolSize، نوشتن majority، compound index، range pagination و explain روی queryهای اصلی
100×، سرویس زیاد، sharding و چند منطقهshard داغ، query پخش‌شده، replication lag و حجم outboxshard key مطابق الگوی دسترسی، read preference مطابق کاربرد، TTL و collection آرشیو، دیتابیس هر سرویس و مدل خواندن پیش‌تجمیع‌شده

آزمایشگاه (Lab) ​

1. اجرای تست‌ها؛ اجرای واقعی ​

bash
export PATH=/opt/homebrew/bin:$PATH
cd docs/snippets/go/mongodb-with-go/go
gofmt -l . ; go vet ./... && go test -race -count=1 ./...
# ok  academy/mongodb-with-go/after
# ok  academy/mongodb-with-go/before
# ok  academy/mongodb-with-go/changes
# ok  academy/mongodb-with-go/connect
# ok  academy/mongodb-with-go/filters
# ok  academy/mongodb-with-go/indexes
# ok  academy/mongodb-with-go/models
# ok  academy/mongodb-with-go/pipelines
# ok  academy/mongodb-with-go/relations
# ok  academy/mongodb-with-go/repo
# ok  academy/mongodb-with-go/schema
# ok  academy/mongodb-with-go/txn
# ok  academy/mongodb-with-go/typed
# ok  academy/mongodb-with-go/updates

این خروجی اجرای واقعی روی Go 1.27.4 در macOS و driver نسخهٔ v2.8.2 است؛ هیچ سرور MongoDB در حال اجرا نبود.

2. دیدن فیلتر تزریق‌شده و ترتیب تصادفی map؛ اجرای واقعی ​

bash
go test -count=1 -v -run TestOperatorInjection ./before | grep filter
# before_test.go:27: filter sent to the server: {"email":"a@example.test","password":{"$ne":""}}
go test -count=1 -v -run TestMapOrder ./filters | grep distinct
# filters_test.go:81: distinct serialisations of one bson.M over 200 runs: 6

عدد دوم بین اجراها فرق می‌کند چون به ترتیب پیمایش map وابسته است. هر عدد بیشتر از 1 نکته را ثابت می‌کند.

3. شکست سریع بدون سرور؛ اجرای واقعی ​

bash
go test -count=1 -v -run TestOpenFails ./connect | grep failed
# connect_test.go:54: failed after 300ms: mongo ping: server selection error: context deadline exceeded,
#   current topology: { Type: Single, Servers: [{ Addr: 127.0.0.1:1, Type: Unknown,
#   Last error: dial tcp 127.0.0.1:1: connect: connection refused }, ] }

4. unique index و duplicate key روی سرور واقعی؛ انتظار می‌رود، اجرا نشده ​

یک replica set تک‌گرهی شروع کنید؛ برای تراکنش و change stream لازم است: mongod --replSet rs0 --dbpath /tmp/rs0 و یک‌بار mongosh --eval 'rs.initiate()'. سپس:

bash
# in mongosh
use shop
db.users.createIndex({ email: 1 }, { unique: true, name: "email_unique" })
db.users.insertOne({ email: "a@example.test", name: "Ada" })
db.users.insertOne({ email: "a@example.test", name: "Ada 2" })
# expected: MongoServerError: E11000 duplicate key error collection: shop.users index: email_unique dup key: { email: "a@example.test" }

با repository در Go، دومین Insert خطایی می‌دهد که هم errors.Is(err, repo.ErrConflict) و هم mongo.IsDuplicateKeyError(err) برایش true است.

5. تراکنشی که retry می‌شود؛ کامپایل‌شده، خروجی مورد انتظار، اجرا نشده ​

اجزا در ماژول نمونه هستند: ledger.Mongo پیاده‌سازی txn.Ledger روی collection به نام accounts است؛ debit با $inc و شرط موجودی در فیلتر، credit با $inc و شمارندهٔ اتمیک DebitCalls برای تعداد تلاش‌ها. فرمان cmd/ledgerlab مجموعهٔ lab.accounts را حذف و seed می‌کند: a برابر 10000 و b برابر 0. سپس روی یک client تعداد 20 فراخوانی هم‌زمان txn.Transfer، هرکدام به مبلغ 100، شروع می‌کند و موجودی‌ها و شمار تلاش‌ها را چاپ می‌کند. بخش خالص، یعنی سندهای فیلتر و update مربوط به debit، unit test دارد. فرمان replica set لازم دارد؛ کامپایل و vet شده، اما اینجا اجرا نشده است.

go
// Package ledger is a MongoDB-backed txn.Ledger: one document per account.
package ledger

import (
	"context"
	"sync/atomic"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"

	"academy/mongodb-with-go/txn"
)

// Account is the document of the accounts collection.
type Account struct {
	ID      string `bson:"_id"`
	Balance int64  `bson:"balance"`
}

// DebitFilter matches the account only while it holds enough money, so the
// check and the write are one atomic operation on one document.
func DebitFilter(account string, cents int64) bson.D {
	return bson.D{
		{Key: "_id", Value: account},
		{Key: "balance", Value: bson.D{{Key: "$gte", Value: cents}}},
	}
}

// Delta is the $inc update for a signed amount.
func Delta(cents int64) bson.D {
	return bson.D{{Key: "$inc", Value: bson.D{{Key: "balance", Value: cents}}}}
}

// Mongo implements txn.Ledger. Every call must receive the transaction ctx.
type Mongo struct {
	Accounts *mongo.Collection
	// DebitCalls counts attempts, including retries of the same transaction.
	DebitCalls atomic.Int64
}

var _ txn.Ledger = (*Mongo)(nil)

// Debit removes cents; zero matches means insufficient funds (or no account).
func (m *Mongo) Debit(ctx context.Context, account string, cents int64) error {
	m.DebitCalls.Add(1)
	res, err := m.Accounts.UpdateOne(ctx, DebitFilter(account, cents), Delta(-cents))
	if err != nil {
		return err // keep the driver error: its labels drive the retry
	}
	if res.MatchedCount == 0 {
		return txn.ErrInsufficientFunds
	}
	return nil
}

// Credit adds cents.
func (m *Mongo) Credit(ctx context.Context, account string, cents int64) error {
	_, err := m.Accounts.UpdateOne(ctx, bson.D{{Key: "_id", Value: account}}, Delta(cents))
	return err
}
bash
# terminal 1: a one-node replica set
mkdir -p /tmp/rs0 && mongod --replSet rs0 --dbpath /tmp/rs0 --port 27017
# terminal 2: initiate once, then run the lab
mongosh --eval 'rs.initiate()'
cd docs/snippets/go/mongodb-with-go/go
MONGODB_URI='mongodb://127.0.0.1:27017/?replicaSet=rs0' go run ./cmd/ledgerlab
# expected, not run:
# transfers=20 failed=0 a=8000 b=2000 debit-attempts=<20 or more>

انتظار می‌رود موجودی نهایی دقیقاً a=8000 b=2000 باشد، چون هر تلاش یا هر دو نوشتن را commit می‌کند یا هیچ‌کدام را. مقدار debit-attempts دست‌کم 20 است؛ اگر دو انتقال هم‌زمان به سندهای یکسان برسند بیشتر می‌شود: تعارض نوشتن، برچسب TransientTransactionError و اجرای دوبارهٔ callback. تعداد retry از اجرا به اجرا فرق می‌کند؛ اگر دقیقاً 20 چاپ شد، تعداد انتقال را در cmd/ledgerlab/main.go بیشتر کنید.

6. صفحه‌بندی بازه‌ای در برابر skip؛ کامپایل‌شده، خروجی مورد انتظار، اجرا نشده ​

فرمان cmd/seeddocs مجموعهٔ lab.items را حذف می‌کند، 1,000,000 سند در دسته‌های 10,000تایی درج می‌کند و _id واقعی جایگاه انتخابی را چاپ می‌کند. آن id با sort روی _id و skip خوانده می‌شود تا یک شناسهٔ واقعی را paste کنید، نه مقدار نمایشی:

bash
MONGODB_URI='mongodb://127.0.0.1:27017/?replicaSet=rs0' go run ./cmd/seeddocs -n 1000000 -pos 900000
# expected, not run: inserted=1000000 id-at-position-900000=<24 hex characters>

سپس با همان id چاپ‌شده دو query را مقایسه کنید:

bash
mongosh lab --eval '
const id = ObjectId("PASTE-THE-PRINTED-ID");
printjson(db.items.find().sort({_id:1}).skip(900000).limit(20).explain("executionStats").executionStats.totalKeysExamined);
printjson(db.items.find({_id:{$gt:id}}).sort({_id:1}).limit(20).explain("executionStats").executionStats.totalKeysExamined);'
# expected, not run: about 900020 for the skip query, about 20 for the range query

برای توسعه‌دهندگان PHP/Laravel ​

Laravel 13 برای MongoDB صفحهٔ مستقل دارد و «installing and using the mongodb/laravel-mongodb package via Composer» را پیشنهاد می‌کند. می‌گوید بسته «is officially maintained by MongoDB» و افزونهٔ PHP به نام mongodb را لازم دارد. در config/database.php یک اتصال با 'driver' => 'mongodb' و dsn برابر MONGODB_URI می‌گذارید. سپس بسته مدل‌های Eloquent ذخیره‌شده در collectionهای MongoDB، با ارث‌بری از MongoDB\Laravel\Eloquent\Model، query builder، رابطه‌های تعبیه‌شده، cache driver آگاه از TTL، queue driver، adapter مربوط به GridFS برای Flysystem و موتور Scout را می‌دهد. تفاوت با Go در شیوهٔ کار است: Laravel همان ORM آشنا را گسترش می‌دهد و BSON را پنهان می‌کند؛ Go driver را می‌دهد تا خودتان لایهٔ نازک را بسازید.

php
// Laravel with mongodb/laravel-mongodb: the same user lookup and a transaction.
$user = User::where('email', $email)->first();            // null when missing, no exception
DB::transaction(function () use ($from, $to, $cents) {   // needs a replica set, like Go
    Account::where('_id', $from)->decrement('balance', $cents);
    Account::where('_id', $to)->increment('balance', $cents);
});

مستند Laravel MongoDB همان قاعدهٔ سرور را بیان می‌کند: «MongoDB standalone deployments do not support transactions». تراکنش تودرتو پشتیبانی نمی‌شود و RuntimeException می‌دهد. traitهای تست RefreshDatabase و DatabaseTransactions هم پشتیبانی نمی‌شوند؛ تست‌ها برای reset داده از DatabaseMigrations استفاده می‌کنند. در Go، پاسخ متناظر به این محدودیت تست، fake پشت interface در همین فصل است.

مقایسه با بستهٔ Laravel MongoDB ​

بستهٔ Laravel MongoDBGo با mongo-go-driver v2
User::where('email', $e)->first() مقدار null می‌دهدFindOne(...).Decode(&u) خطای mongo.ErrNoDocuments می‌دهد
attribute و cast در Eloquentفیلد struct و tagهای bson
User::create([...])InsertOne
$user->increment('logins')UpdateOne با $inc
رابطهٔ تعبیه‌شده که بسته ارائه می‌دهدslice تعبیه‌شده از structها
relation در Eloquent یا aggregation خاممرحلهٔ $lookup در mongo.Pipeline
DB::transaction(fn)session.WithTransaction(ctx, fn)
ساخت index با migration یا job راه‌اندازیIndexes().CreateMany در شروع یا job
RefreshDatabase پشتیبانی نمی‌شودfake یا سرور واقعی برای هر اجرای تست
چرخهٔ درخواست بدون cancellationctx روی هر فراخوانی

بدفهمی‌های رایج ​

باورواقعیت
mongo.Connect با خاموش بودن سرور شکست می‌خوردفقط گزینه‌ها را اعتبارسنجی می‌کند؛ Ping بزنید
bson.M و bson.D جای هم می‌آیندbson.M ترتیب ندارد؛ sort، کلید index و فرمان bson.D لازم دارند
FindOne در نبود تطبیق nil می‌دهدDecode خطای mongo.ErrNoDocuments می‌دهد
نتیجهٔ خالی Find خطاستcursor خالی است
UpdateOne در نبود تطبیق خطا می‌دهدبا MatchedCount == 0 موفق می‌شود
All، cursor را باز می‌گذاردخودش می‌بندد؛ حلقهٔ Next باید ببندد
omitempty هر struct صفر را حذف می‌کندفقط struct با IsZero برابر true، مثل time.Time؛ struct معمولی می‌ماند
InsertMany اتمیک استدرخواست دسته‌ای است؛ driver بالاتر از 100,000 نوشتن خردش می‌کند؛ با شکست سند بعدی، قبلی‌ها می‌مانند
تراکنش روی هر سرور کار می‌کندفقط replica set یا sharded cluster
callback در WithTransaction یک بار اجرا می‌شودممکن است چند بار اجرا شود؛ باید idempotent باشد
timeout روی context نوشتن سرور را لغو می‌کندclient انتظار را متوقف می‌کند؛ نوشتن شاید اعمال شود
MongoDB بدون schema است، پس طراحی لازم نیستstruct، index، validator و انتخاب embed/reference همان schema هستند
skip صفحه‌بندی ارزانی استهزینه با offset رشد می‌کند؛ بازه روی _id بگذارید
repository جنریک دیتابیس را تعویض‌پذیر می‌کندخطا و تست را متمرکز می‌کند؛ فیلتر هنوز سند MongoDB است

یادسپار (Cheat sheet) ​

موضوعچه چیزی را حفظ باشید
ماژولgo.mongodb.org/mongo-driver/v2؛ در v2، mongo.Connect(opts) پارامتر ctx ندارد
Clientیکی برای هر پردازه؛ Ping در شروع و Disconnect در خاموشی
گزینه‌هااول options.Client().ApplyURI(uri)، سپس setterها؛ پیش‌فرض MaxPoolSize برابر 100 و انتخاب سرور 30 s
Contextctx مشتق‌شده با timeout برای هر فراخوانی؛ deadline بر Timeout در client مقدم است
BSONbson.D برای هر چیز مرتب؛ bson.M فقط خواندن شکل ناشناخته؛ bson.ObjectID برای id
Tag_id,omitempty، omitempty، inline، -؛ بدون tag یعنی نام lowercase
خواندن یکیFindOne(...).Decode(&v)؛ errors.Is(err, mongo.ErrNoDocuments)
خواندن چندتاFind، defer cur.Close(ctx)، All محدود یا Next/Decode و سپس cur.Err()
صفحه‌بندیبازهٔ _id برای feed؛ هزینهٔ skip با offset رشد می‌کند
Updateoperatorهای $set، $inc، $push، $addToSet؛ شرط محافظ در فیلتر؛ بررسی MatchedCount
Upsertهمراه unique index؛ $setOnInsert برای فیلد فقط‌هنگام‌ساخت
IndexIndexes().CreateOne/CreateMany؛ کلیدها bson.D؛ ترتیب ESR؛ TTL حدود هر 60 s اجرا می‌شود
Aggregationmongo.Pipeline، ابتدا $match؛ $lookup به index روی فیلد خارجی نیاز دارد
رابطهدادهٔ محدود و خوانده‌شده با هم را embed و باقی را reference کنید؛ snapshot با برنامه
تراکنشreplica set یا sharded؛ WithTransaction؛ callback idempotent؛ استفاده از ctx callback
خطاIsDuplicateKeyError با 11000، IsTimeout، ErrNoDocuments؛ نگاشت در یک مرز
Validation$jsonSchema با SetValidator یا collMod؛ رد شدن با کد 121
تستinterface + fake با NewCursorFromDocuments؛ سرور واقعی برای index، TTL و تراکنش

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — mongo.Connect بدون خطا برگشت؛ آیا دیتابیس در دسترس است؟ حیاتی ​

پاسخ

پاسخ: لزوماً نه. mongo.Connect فقط برای گزینهٔ نامعتبر خطا می‌دهد و برای بررسی دسترسی با سرور تماس نمی‌گیرد. در شروع client.Ping(ctx, readpref.Primary()) را با timeout کوتاه اجرا کنید. سرور دور از دسترس پس از مهلت انتخاب سرور، یعنی پیش‌فرض 30 ثانیه با تنظیم SetServerSelectionTimeout، خطای server selection می‌دهد؛ اتصال.

۲ — چرا سند sort باید bson.D باشد، نه bson.M؟ حیاتی ​

پاسخ

پاسخ: ترتیب کلید در sort، کلید index و فرمان بخشی از معناست؛ پیمایش map در Go ترتیب تصادفی دارد. به همین دلیل driver برای sort یا hint از نوع bson.M چندکلیدی ErrMapForOrderedArgument می‌دهد. تست این فصل یک bson.M شش‌کلیدی را 200 بار serialize کرد و چند ترتیب متفاوت گرفت؛ bson.D همیشه ترتیب نوشته‌شده را نگه می‌دارد؛ نوع‌های BSON.

۳ — کاربر {"password": {"$ne": ""}} را به endpoint ورود می‌فرستد؛ باگ چگونه شکل می‌گیرد و چطور جلویش را می‌گیرید؟ حیاتی ​

پاسخ

پاسخ: اگر handler فیلدهای درخواست را داخل فیلتر bson.M کپی کند، object به سند operator تبدیل می‌شود و هر حساب دارای رمز را تطبیق می‌دهد. struct درخواست با فیلد string بگیرید، چون object داخل string decode نمی‌شود؛ builder فیلتر ورودی تایپ‌دار بگیرد؛ و رمز را به‌جای گذاشتن در query، در Go با hash ذخیره‌شده مقایسه کنید؛ Go: قبل و بعد.

۴ — omitempty با bson.ObjectID، time.Time، pointer برابر nil و struct معمولی چه می‌کند؟ مهم ​

پاسخ

پاسخ: ObjectID صفر و time.Time صفر را حذف می‌کند، چون هر دو IsZero دارند؛ pointer برابر nil هم حذف می‌شود. struct معمولی بدون IsZero هرگز خالی حساب نمی‌شود و به‌شکل سند فرعی نوشته می‌شود؛ برای همین سند فرعی اختیاری باید pointer باشد. omitzero در v2.8.2 یک tag این بسته نیست؛ نگاشت struct.

۵ — FindOne چیزی پیدا نکرد؛ چه می‌گیرید و Find با همان فیلتر چه می‌دهد؟ حیاتی ​

پاسخ

پاسخ: FindOne(...).Decode(&v) خطای mongo.ErrNoDocuments می‌دهد که با errors.Is مقایسه می‌کنید. Find یک cursor خالی و بدون خطا می‌دهد. repository باید اولی را به خطای پیدا‌نشدن خودش تبدیل کند؛ FindOne و Find و cursor.

۶ — چه وقت باید cursor.Close را صدا بزنید و All چه می‌کند؟ تکمیلی ​

پاسخ

پاسخ: هر وقت با Next می‌خوانید، همیشه cursor را ببندید، وگرنه سرور منابعش را نگه می‌دارد؛ عادت درست defer cur.Close(ctx) بلافاصله پس از بررسی خطاست. All بعد از خواندن همهٔ سندها خودش cursor را می‌بندد، ولی برگشت زودهنگام پیش از All هنوز deferred close لازم دارد. بعد از حلقهٔ Next، cur.Err() را هم بخوانید؛ Find و cursor.

۷ — چرا صفحه‌بندی بازه‌ای روی _id در صفحهٔ 10,000 از limit/skip سریع‌تر است و چه قابلیتی را از دست می‌دهید؟ حیاتی ​

پاسخ

پاسخ: skip سرور را وادار می‌کند همهٔ ورودی‌های ردشده را طی کند؛ هزینه با offset زیاد می‌شود. فیلتر _id > last مستقیم به موقعیت index می‌رود، پس هزینهٔ هر صفحه یکسان است. در عوض پرش به شمارهٔ صفحهٔ دلخواه ندارید و کلید sort باید یکتا و indexشده باشد؛ صفحه‌بندی.

۸ — چرا به‌جای خواندن شمارنده، افزودن یک و ذخیره، از $inc استفاده می‌کنید؟ مهم ​

پاسخ

پاسخ: خواندن‌تغییر‌نوشتن race دارد: دو درخواست یک مقدار را می‌خوانند و نوشتن دوم اولی را پاک می‌کند؛ همان lost update. $inc برای آن سند اتمیک روی سرور اعمال می‌شود. برای «فقط اگر موجودی کافی بود»، شرط را در فیلتر بگذارید و MatchedCount را بررسی کنید؛ به‌روزرسانی.

۹ — چه وقت embed و چه وقت reference می‌کنید؟ مهم ​

پاسخ

پاسخ: داده‌ای را embed کنید که با والد خوانده می‌شود، اندازهٔ محدود دارد و مستقل زندگی نمی‌کند؛ مانند خط‌های سفارش. دادهٔ مشترک، پرتغییر، مستقل در query یا دارای رشد نامحدود را reference کنید و با $lookup یا query دوم join کنید. چند فیلد را فقط وقتی به‌شکل snapshot کپی کنید که کهنه شدن کپی را می‌پذیرید. سند نباید از 16 MiB بیشتر شود؛ رابطه‌ها.

۱۰ — callback در WithTransaction چه الزام‌هایی دارد و روی کدام استقرار اجرا می‌شود؟ حیاتی ​

پاسخ

پاسخ: روی replica set یا sharded cluster اجرا می‌شود، نه سرور standalone. callback ممکن است چند بار اجرا شود؛ پس باید idempotent و بدون اثر جانبی مثل ایمیل باشد. هر عملیات داخل آن باید همان ctx دریافتی callback را استفاده کند و خطاها باید برگردند، نه پنهان شوند. driver تراکنش گذرا را تا 120 ثانیه retry می‌کند؛ تراکنش‌ها.

۱۱ — unique index درج دوم را رد می‌کند؛ کدام کد و helper را بررسی می‌کنید و صدازننده چه می‌بیند؟ مهم ​

پاسخ

پاسخ: کد سرور 11000 با نام DuplicateKey است. mongo.IsDuplicateKeyError(err) آن را حتی داخل خطای bulk تشخیص می‌دهد. repository آن را به ErrConflict خودش تبدیل و با %w wrap می‌کند تا خطای driver در زنجیره بماند؛ handler HTTP آن را به 409 تبدیل می‌کند؛ مدیریت خطا.

۱۲ — بدون سرور MongoDB، کد استفاده‌کننده از driver را چطور تست می‌کنید؟ تکمیلی ​

پاسخ

پاسخ: شش متد مصرفی را پشت interface کوچک بگذارید و fakeی بسازید که نتیجه را از mongo.NewCursorFromDocuments و mongo.NewSingleResultFromDocument می‌سازد؛ decode از codec واقعی BSON عبور می‌کند. فیلتر و pipeline را با bson.MarshalExtJSON تست کنید. helper خود driver به نام mtest در v2 داخلی است و import نمی‌شود. برای index، TTL، تراکنش و change stream از mongod واقعی یا testcontainers استفاده کنید؛ تست.

۱۳ — resume token در change stream به چه کار می‌آید؟ تکمیلی ​

پاسخ

پاسخ: هر رویداد token دارد. اگر token آخرین رویداد پردازش‌شده را ذخیره و موقع باز کردن دوبارهٔ stream به SetResumeAfter بدهید، stream از بعد همان رویداد ادامه می‌دهد؛ restart تغییری را از دست نمی‌دهد، به‌شرط اینکه oplog هنوز فاصله را پوشش دهد. پردازش at-least-once است؛ پس handler باید idempotent باشد؛ Change stream و GridFS.

واژه‌نامه (Glossary) ​

اصطلاحمعنا
mongo-go-driver v2driver رسمی MongoDB برای Go با ماژول go.mongodb.org/mongo-driver/v2
mongo.Clienthandle مالک pool اتصال و monitorها؛ یکی در هر پردازه
mongo.Connectساخت client از گزینه‌ها؛ دسترسی به سرور را ثابت نمی‌کند
options.Clientbuilder گزینه‌های client مانند ApplyURI، SetMaxPoolSize و SetTimeout
ApplyURIparse رشتهٔ اتصال به گزینه‌های client؛ setter بعدی بر آن مقدم است
Pingفرمان کم‌هزینه برای بررسی امکان انتخاب سرور
Disconnectبستن pool و توقف monitor، با انتظار برای اتصال‌های در حال استفاده
مهلت context (Context timeout)deadline روی ctx که عملیات را در سمت client محدود می‌کند
BSONقالب دودویی سند برای ذخیره و انتقال در MongoDB
bson.Dسند مرتب؛ slice از bson.E
bson.Mسند نامرتب؛ map در Go
bson.Aآرایهٔ BSON؛ slice مقدارها
برچسب struct (Struct tag)فراداده‌ای مانند bson:"name,omitempty" برای کنترل نگاشت
_idکلید اصلی اجباری هر سند، یکتا و indexشده
bson.ObjectIDشناسهٔ 12بایتی با timestamp ساخت درون خودش
omitemptyگزینهٔ tag برای حذف مقدار خالی، از جمله struct دارای IsZero
inlineگزینهٔ tag برای باز کردن struct یا map تعبیه‌شده در والد
ErrNoDocumentsخطای sentinel خواندن تک‌سندی بدون نتیجه
مکان‌نما (Cursor)handle نتیجهٔ سمت سرور که با Next دسته‌دسته خوانده می‌شود
فیلتر (Filter)سند توصیف‌کنندهٔ شرط تطبیق سندها
گزینش فیلد (Projection)تعیین فیلدهایی که خواندن برمی‌گرداند
صفحه‌بندی بازه‌ای (Range pagination)گرفتن «بعد از آخرین _id» به‌جای skip
$set، $inc، $push، $addToSetoperatorهای update: انتساب، افزایش، افزودن و افزودن در صورت غیبت
درج یا تغییر (Upsert)update که در نبود تطبیق insert می‌کند
$setOnInsertoperator فقط مخصوص insert در upsert
نوشتن دسته‌ای (Bulk write)ارسال چند مدل نوشتن متفاوت در دسته‌های حداکثر 100,000تایی
نمایه (Index)ساختار جانبی مرتب برای جست‌وجوی سریع
نمایهٔ یکتا (Unique index)index ردکنندهٔ کلید تکراری با کد 11000
نمایهٔ مرکب (Compound index)index روی چند فیلد که ترتیبشان مهم است
نمایهٔ TTL (TTL index)index روی فیلد date برای حذف سند پس از تأخیر
نمایهٔ متنی (Text index)index جست‌وجوی واژه روی فیلد رشته‌ای
Pipeline تجمیع (Aggregation pipeline)فهرست مرتب مرحله‌های تبدیل سند
$lookupمرحلهٔ pipeline برای join با collection دیگر
$unwindمرحلهٔ pipeline با یک سند خروجی برای هر عضو آرایه
تعبیه (Embedding)ذخیرهٔ دادهٔ مرتبط داخل سند والد
ارجاع (Referencing)ذخیرهٔ id سند مرتبط
غیرنرمال‌سازی (Denormalization)تکرار داده برای ارزان‌تر کردن خواندن
Repository[T]نوع جنریک پوشانندهٔ collection برای سندهای نوع T
فیلتر تایپ‌دار (Typed filter)builder فیلتر با بررسی نوع مقدارها توسط کامپایلر Go
نشست (Session)context سمت سرور که تراکنش در آن اجرا می‌شود
WithTransactionاجرای callback داخل تراکنش با retry خودکار خطای گذرا
مجموعهٔ replica (Replica set)گروه سرورهای دارای دادهٔ یکسان با یک primary
تضمین خواندن / نوشتن (Read concern / Write concern)ایمنی لازم برای خواندن / تعداد عضوهای تأییدکنندهٔ نوشتن
جریان تغییرات (Change stream)خوراک زندهٔ تغییرها با امکان ادامه از token
GridFSقرارداد ذخیرهٔ فایل بزرگ به‌شکل chunk در دو collection
$jsonSchemaقواعد اعتبارسنجی متصل به collection
کلید تکراری (Duplicate key)خطای 11000 ناشی از نقض unique index
MaxPoolSizeبیشترین اتصال به هر سرور در pool یک client؛ پیش‌فرض 100
بدل جعلی (Fake)پیاده‌سازی تستی interface به‌جای سرور واقعی
testcontainersکتابخانه‌ای برای اجرای container واقعی MongoDB در اجرای تست

منابع ​

ساخته‌شده توسط Morteza Negahi