惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
C
Check Point Blog
GbyAI
GbyAI
博客园 - 司徒正美
爱范儿
爱范儿
N
Netflix TechBlog - Medium
H
Hacker News: Front Page
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - Franky
Recent Announcements
Recent Announcements
P
Privacy International News Feed
T
Tor Project blog
Y
Y Combinator Blog
有赞技术团队
有赞技术团队
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
G
GRAHAM CLULEY
The Hacker News
The Hacker News
N
News and Events Feed by Topic
I
Intezer
The GitHub Blog
The GitHub Blog
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
IT之家
IT之家
T
Threat Research - Cisco Blogs
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
DataBreaches.Net
Hacker News - Newest:
Hacker News - Newest: "LLM"
Last Week in AI
Last Week in AI
H
Help Net Security
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
Help Net Security
Help Net Security
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Google Online Security Blog
Google Online Security Blog
Cyberwarzone
Cyberwarzone
T
Tailwind CSS Blog
V
Vulnerabilities – Threatpost
Forbes - Security
Forbes - Security
Apple Machine Learning Research
Apple Machine Learning Research
O
OpenAI News
AWS News Blog
AWS News Blog
月光博客
月光博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Clean Architecture in MongoDB + C#: Why is the Repository Pattern Alone Not Enough?
Filipe Neves · 2026-05-27 · via DEV Community

This article is based on a public repository I created. You can check the full project and follow here: MongoIntegrationAPI

Ever since I started using C# and writing my first lines of code, I was trained to apply the Clean Architecture pattern. Following DDD principles, I focused on the Domain layer, keeping it separated from Infrastructure and completely unaware that entities could represent a database table.

When I got my first MongoDB project, I had several problems. The MongoDB driver expects some specific methods to search and insert data, instances are built differently, and all of this made my first experience a traumatic one.

It turns out that stepping outside my comfort zone gives me motivation and energy to study and understand things. I started building Proofs of Concept (POCs), trying the connection between C# .NET and MongoDB in different scenarios. Working on these projects, I started to feel something was wrong again, I missed the Generic Repository Pattern and all the ease of dependency injection.

I also noticed another point about MongoDB: because it is a document-oriented database, it structures its “tables” differently. We can make a simple analogy where Tables are Collections and Rows are Documents. A document looks a lot like JSON, but it’s not. Actually, it’s BSON, a binary version.

The difference is that BSON is designed for storage efficiency. It stores metadata such as length and type, because of that it can be parsed and analyzed much more quickly by machines than JSON text. BSON supports basic types such as strings, bools, and numbers, and also some extra types such as dates, binaries, and exclusive identifiers like ObjectIds.

Book:

{
  "_id": { "$oid": "69bc53b77b02eb421c958688" },
  "title": "Dune"
}

Enter fullscreen mode Exit fullscreen mode

In software, we deal with data that is frequently accessed together. In situations like this, we can create an Embedded Document. Embedding is basically placing one document, or an array of documents, inside a field of another parent document.

There are a lot of embedded data patterns such as the Subset Pattern, Extended Reference Pattern, and Computed Pattern. All of them fit different scenarios.

The same book, “Dune”, but now as an Embedded Document:

{
  "_id": { "$oid": "69bc53b77b02eb421c958688" },
  "title": "Dune",
  "publisherId": { "$oid": "69bc53957b02eb421c958687" },
  "authors": [
    {
      "name": "Frank Herbert",
      "bibliography": "[...]"
    }
  ],
  "categories": [
    {
      "name": "SciFi",
      "description": "Science fiction exploring the future and technology."
    },
    {
      "name": "Adventure",
      "description": "Stories focused on journeys, challenges, and discoveries."
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

In C#, our classes require specific annotations which, although functional, introduce coupling with the Infrastructure layer. This reduces portability and violates the separation of concerns proposed by Clean Architecture.

Let’s talk more about how we learn to build systems by checking the TreeView of the project.

3 folders, no separation between domain and storage

C:\...\MongoIntegrationAPI\
├───Controllers\            <-- Depend directly on the concrete repository classes
├───Models\                 <-- Entities decorated with [BsonId], [BsonRepresentation], [BsonElement]
├───Repositories\           <-- Use IMongoCollection<> directly — the MongoDB driver leaks in here
├───MongoContext.cs         <-- Exposes IMongoCollection<T> to the whole application
└───MongoSettings.cs        <-- Connection settings

Enter fullscreen mode Exit fullscreen mode

Taking a closer look, focusing on a small entity shown in the BSON, the Book. This Book class is a main entity which has its own attributes. For the examples, we'll use a simplified version.

Let’s see how our Book is translated into C#:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class Book
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = string.Empty;

    [BsonElement("title")]
    public string Title { get; set; } = string.Empty;

    [BsonElement("publisherId")] 
    [BsonRepresentation(BsonType.ObjectId)]
    public string PublisherId { get; set; } = string.Empty;

    [BsonElement("authors")]
    public List<AuthorInBook> Authors { get; set; } = new();

    [BsonElement("categories")]
    public List<Category> Categories { get; set; } = new();
}

public class AuthorInBook
{
    [BsonElement("name")]
    public string Name { get; set; } = string.Empty;

    [BsonElement("bibliography")]
    public string Bibliography { get; set; } = string.Empty;
}

public class Category
{
    [BsonElement("name")]
    public string Name { get; set; } = string.Empty;

    [BsonElement("description")]
    public string Description { get; set; } = string.Empty;
}

Enter fullscreen mode Exit fullscreen mode

Adding it to the context:

using MongoDB.Driver;

public class MongoContext
{
    private readonly IMongoDatabase _database;

    public MongoContext(MongoSettings settings)
    {
        var client = new MongoClient(settings.ConnectionString);
        _database = client.GetDatabase(settings.DatabaseName);
    }

    public IMongoCollection<Book> Books =>
        _database.GetCollection<Book>("books");
}

Enter fullscreen mode Exit fullscreen mode

Being used in the Repository:

using MongoDB.Driver;

public class BookRepository
{
    private readonly IMongoCollection<Book> _collection;

    public BookRepository(MongoContext context)
    {
        _collection = context.Books; 
    }

    public async Task<List<Book>> GetAllAsync()
    {
        return await _collection.Find(_ => true).ToListAsync();
    }

    public async Task<Book?> GetByIdAsync(string id)
    {
        return await _collection.Find(x => x.Id == id).FirstOrDefaultAsync();
    }

    public async Task CreateAsync(Book book)
    {
        await _collection.InsertOneAsync(book);
    }
}

Enter fullscreen mode Exit fullscreen mode

Analyzing the code, it’s possible to identify what is described as “infrastructure infection”. Some layers of this project are infected by the MongoDB driver. Entities and the repository import it, and the controller/service layer depends on these classes.

Although the implementation is simple and functional at first glance with our Book model, it introduces some unnecessary coupling that will make the system harder to evolve.

The entity now depends on MongoDB attributes such as ObjectId, which means that business rules become tied to persistence details, reducing Domain independence and making changes in drivers or storage impact parts of the system that, in theory, should be stable.

The repository, in turn, fails to fully fulfill its role as an abstraction. Instead of isolating data access, it only wraps direct calls to the MongoDB driver, making the code tightly coupled to the driver’s API.

private readonly IMongoCollection<Book> _collection;

The Repository is not just using the database anymore. The MongoDB driver is shaping everything and forcing the Book class to satisfy the driver.

It limits the flexibility of the entire application. This coupling directly impacts testability, since the driver's dependency on interfaces makes creating mocks more complex and, in many cases, leads to an overreliance on integration tests.

Can you imagine what could happen if the developer received a task to switch databases or export all entities to a library? It would not be a refactor, it would be a rewrite.

This type of approach, even being common in introductory examples, puts the database as one of the central elements of our software while the Domain starts to play a secondary role.

All of this goes against Clean Architecture principles, which propose exactly the opposite: a system driven by behavior and business rules, with infrastructure being only an external detail.

A Way Out: Translation Layer and Atomic Operations

To guarantee everyone can understand how the proposed isolation works and materializes in practice, it’s essential to understand the project organization.

The folder structure is not just a style choice, but a direct representation of our architectural decisions, establishing clear boundaries between business rules and persistence details:

C:\...\MongoIntegrationAPI\
├───Domain\
│   ├───Entities\           <-- Pure POCOs (Author.cs, Book.cs)
│   ├───Enums\
│   └───Interfaces\         <-- Contracts (IBookRepository.cs)
├───Infrastructure\
│   ├───DataModels\         <-- BSON-decorated models (BookDataModel.cs)
│   ├───Repositories\       <-- Implementations and mappings
│   ├───Daos\               <-- MongoDB-specific operations
│   └───MongoDbSetup.cs     <-- Configuration
└───Controllers\            <-- Application entry point

Enter fullscreen mode Exit fullscreen mode

Inside Infrastructure, we’re going to have three types of classes:

  • Specific repositories such as BookRepository to receive Domain entities, transform them into DataModels, and move them to database actions.
  • A Generic Repository to provide easier access and reusable CRUD methods, receiving DataModels as parameters and never knowing about the Domain.
  • Specific DAOs such as BookDao, a precision tool for MongoDB atomic operations.

Inside the Domain directory lies the core of our system, composed exclusively of essential business elements. The entities are defined as simple objects without any dependency on external libraries, while interfaces guarantee clear contracts about what the system needs to do.

This layer represents the application’s behavior and must stay isolated from any technical detail.

In this model, there is no indication of how the data will be persisted in the database. The focus is exclusively on representing the business.

// Domain layer
public class Book
{
   public string Id { get; set; } = string.Empty;
   public string Title { get; set; } = string.Empty;
   public string PublisherId { get; set; } = string.Empty;
   public List<AuthorInBook> Authors { get; set; } = new();
   public List<Category> Categories { get; set; } = new();
}

public class AuthorInBook
{
    public string Id { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
}

Enter fullscreen mode Exit fullscreen mode

You can notice that our Book entity carries embedded information from our Author, just like the BSON shown earlier, but now it’s not a database decision anymore, it comes from business rules.

The Book entity is loaded, validated, and persisted together with categories and authors, so we create it this way in the Domain.

The difference now is that business operations made us design the entity with these attributes, and MongoDB just respects this with embedding patterns.

If you would keep this shape even with another database, it’s a Domain choice. Otherwise, the database is still in charge.

On the other hand, the Infrastructure folder focuses on all persistence decisions. This is where DataModels live, responsible for handling specific MongoDB features.

The concrete repositories make the bridge between Domain and Database. This organization ensures the complexity stays contained, preventing it from “leaking” into the rest of the system:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoIntegrationAPI.Infrastructure.Attributes;

namespace MongoIntegrationAPI.Infrastructure.DataModels
{
    // Infrastructure layer: storage decisions
    [CollectionName("books")]
    public class BookDataModel
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string? Id { get; set; }

        public string Title { get; set; } = string.Empty;

        [BsonRepresentation(BsonType.ObjectId)]
        public string PublisherId { get; set; } = string.Empty;

        // The database stores nested objects to optimize reads
        public List<AuthorEmbeddedModel> Authors { get; set; } = new();

        public List<CategoryEmbeddedModel> Categories { get; set; } = new();
    }
}

Enter fullscreen mode Exit fullscreen mode

DataModel is where we isolate all persistence-related decisions, such as the use of ObjectId and embedding structures. This allows us to optimize persistence without affecting the Domain.

Reading our DataModel, it’s possible to notice [CollectionName("books")]. It’s not from MongoDB, it’s from our architecture to make it easier to use our Generic Repository pattern.

We’ll use MongoDB, but how can we use just one class to control the commands here?

Let’s start by looking into how these classes work together, beginning with the new attribute in the DataModel.

The interface:

namespace MongoIntegrationAPI.Infrastructure.Repositories
{
    public interface IGenericRepository<TDocument> where TDocument : class
    {
        Task AddAsync(TDocument document);
        Task<TDocument?> GetByIdAsync(string id);
        Task<IEnumerable<TDocument>> GetAllAsync();
        Task ReplaceAsync(string id, TDocument document);
        Task DeleteAsync(string id);
    }
}

Enter fullscreen mode Exit fullscreen mode

The implementation:

using MongoDB.Bson;
using MongoDB.Driver;
using MongoIntegrationAPI.Infrastructure.Attributes;
using System.Reflection;

namespace MongoIntegrationAPI.Infrastructure.Repositories
{
    public class GenericRepository<TDocument> : IGenericRepository<TDocument> where TDocument : class
    {
        private readonly IMongoCollection<TDocument> _collection;

        public GenericRepository(IMongoDatabase database)
        {
            var collectionName = typeof(TDocument)
                .GetCustomAttribute<CollectionNameAttribute>()?.Name
                ?? typeof(TDocument).Name;

            _collection = database.GetCollection<TDocument>(collectionName);
        }

        public async Task AddAsync(TDocument document)
        {
            await _collection.InsertOneAsync(document);
        }

        public async Task<IEnumerable<TDocument>> GetAllAsync()
        {
            return await _collection.Find(Builders<TDocument>.Filter.Empty).ToListAsync();
        }

        public async Task<TDocument?> GetByIdAsync(string id)
        {
            var filter = Builders<TDocument>.Filter.Eq("_id", new ObjectId(id));
            return await _collection.Find(filter).FirstOrDefaultAsync();
        }

        public async Task ReplaceAsync(string id, TDocument document)
        {
            var filter = Builders<TDocument>.Filter.Eq("_id", new ObjectId(id));
            await _collection.ReplaceOneAsync(filter, document);
        }

        public async Task DeleteAsync(string id)
        {
            var filter = Builders<TDocument>.Filter.Eq("_id", new ObjectId(id));
            await _collection.DeleteOneAsync(filter);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The constructor of our Repository asks for an IMongoDatabase to get the Collection found by the collectionName, which is the result of our CollectionNameAttribute on the DataModel.

namespace MongoIntegrationAPI.Infrastructure.Attributes
{
    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
    public class CollectionNameAttribute : Attribute
    {
        public string Name { get; }

        public CollectionNameAttribute(string name)
        {
            Name = name;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

The main point of this architecture is the role of the specific repository as a translator whenever the Domain and DataModel shapes diverge, which is almost always the case in real systems.

It’s no longer a passive intermediary. It explicitly converts the data between the two models and calls the generic version to make updates:

// Infrastructure
public async Task AddAsync(Book book)
{
   var dataModel = new BookDataModel
   {
       Title = book.Title,
       PublisherId = book.PublisherId,
       Authors = book.Authors
           .Select(a => new AuthorEmbeddedModel
           {
               Id = a.Id,
               Name = a.Name
           })
           .ToList()
   };

   await _genericRepository.AddAsync(dataModel);

   // We adopt the native ObjectId pragmatically,
   // reflecting it back into the Domain after creation
   book.Id = dataModel.Id!;
}

Enter fullscreen mode Exit fullscreen mode

This section works as a barrier against the corruption of responsibilities, acting as an anti-corruption layer.

Database changes stop here in these repositories, allowing us to maintain the stability of our business rules while the Generic Repository only receives DataModel objects.

These repositories work well for translating documents. Now let’s analyze performance scenarios in MongoDB.

Loading a massive embedded document into memory just to add a single field into an array is a waste of resources. This is the point where we need a new layer responsible for leveraging specific MongoDB features.

The new layer is going to be the Data Access Object (DAO).

Think of it like a hospital. The Repository is the reception desk. You go there to find a patient, schedule an appointment, or retrieve a record.

The DAO is the specialist who walks into the archives room, knows exactly which folder to pull, and updates a single page without taking the whole file off the shelf.

// Infrastructure layer: BookDao.cs (atomic performance)
public async Task<bool> AddAuthorToBookAtomicAsync(string bookId, AuthorEmbeddedModel author)
{
    var filter = Builders<BookDataModel>.Filter.Eq(b => b.Id, bookId);

    var update = Builders<BookDataModel>.Update.Push(b => b.Authors, author);

    var result = await _collection.UpdateOneAsync(filter, update);

    return result.MatchedCount > 0;
}

Enter fullscreen mode Exit fullscreen mode

In document database design, there exists a fundamental rule:

“Data that's accessed together should be stored together.”

Embeddings help us follow this rule and create denormalization that is very useful for reads, but can make updates very costly.

By coupling this logic into the DAO, we solve this problem.

Instead of loading the entire Book into the application, changing it with C#, and rewriting the whole document, we use the $push operator to alter only the necessary fragment directly in the database.

The Repository orchestrates the business flow, but only the DAO knows the syntax and atomic operations of the MongoDB driver.

The final result is an architecture where Embedding becomes a clear storage decision and the DAO becomes a precision tool to manipulate data.

In the project, it becomes evident that the BookRepository exposes a clear method to add an Author, while internally using the DAO to submit the surgical update of the BSON document.

With this, we can reach the best of both worlds: a behavior-focused Domain supported by an Infrastructure layer capable of extracting all the performance MongoDB can offer, without either side needing to know the other’s technical details.