当前位置: 首页 > ai >正文

mongodb源代码分析创建db流程分析

mongo/db/catalog/create_collection.cpp中reateCollection构建元数据文档:将集合信息(命名空间、选项、键前缀等)序列化为 BSON 格式,{ ns: "db.conca", ident: "collection-0--8262702921578327518", md: };
_rs->insertRecord将元数据文档插入到Catalog的记录存储(RecordStore)中,写入到系统表_uri:table:_mdb_catalog中。_mdb_catalog存储集合和索引的元数据信息,_mdb_catalog.wt在数据库文件夹下面:

数据库的信息在哪个文件存储呢?

/mongo/db/catalog/create_collection.cpp是创建集合的核心代码,后面重点分析其中获取数据库的代码。

mongo/db/catalog/create_collection.cpp中_createCollection是命令db.createCollection('conca', { })核心方法。AutoGetOrCreateDb autoDb先获取到对应的数据库。

Status _createCollection(OperationContext* opCtx,const NamespaceString& nss,const CollectionOptions& collectionOptions,const BSONObj& idIndex) {...AutoGetOrCreateDb autoDb(opCtx, nss.db(), MODE_IX);Lock::CollectionLock collLock(opCtx, nss, MODE_X);...});
}

/mongo/db/catalog_raii.cpp中AutoGetOrCreateDb代码,_autoDb.getDb()获取数据库,如果没有获取到db,openDb则进行打开对应的数据库。

AutoGetOrCreateDb::AutoGetOrCreateDb(OperationContext* opCtx,StringData dbName,LockMode mode,Date_t deadline): _autoDb(opCtx, dbName, mode, deadline) {invariant(mode == MODE_IX || mode == MODE_X);_db = _autoDb.getDb();if (!_db) {auto databaseHolder = DatabaseHolder::get(opCtx);_db = databaseHolder->openDb(opCtx, dbName, &_justCreated);}auto dss = DatabaseShardingState::get(opCtx, dbName);auto dssLock = DatabaseShardingState::DSSLock::lockShared(opCtx, dss);dss->checkDbVersion(opCtx, dssLock);
}

 /mongo/db/catalog/database_holder_impl.cpp中openDb代码:

 std::make_unique<DatabaseImpl>(dbname, ++_epoch)创建数据库实现类DatabaseImpl, newDb->init初始化数据库实现类。auto it = _dbs.find(dbname);再次获取是否存在相同名称的数据库,如果存在则返回,如果不存在则设置进去。

Database* DatabaseHolderImpl::openDb(OperationContext* opCtx, StringData ns, bool* justCreated) {const StringData dbname = _todb(ns);invariant(opCtx->lockState()->isDbLockedForMode(dbname, MODE_IX));if (justCreated)*justCreated = false;  // Until proven otherwise.stdx::unique_lock<SimpleMutex> lk(_m);// The following will insert a nullptr for dbname, which will treated the same as a non-// existant database by the get method, yet still counts in getNamesWithConflictingCasing.if (auto db = _dbs[dbname])return db;// We've inserted a nullptr entry for dbname: make sure to remove it on unsuccessful exit.auto removeDbGuard = makeGuard([this, &lk, dbname] {if (!lk.owns_lock())lk.lock();_dbs.erase(dbname);});// Check casing in lock to avoid transient duplicates.auto duplicates = _getNamesWithConflictingCasing_inlock(dbname);uassert(ErrorCodes::DatabaseDifferCase,str::stream() << "db already exists with different case already have: ["<< *duplicates.cbegin() << "] trying to create [" << dbname.toString()<< "]",duplicates.empty());// Do the catalog lookup and database creation outside of the scoped lock, because these may// block.lk.unlock();if (CollectionCatalog::get(opCtx).getAllCollectionUUIDsFromDb(dbname).empty()) {audit::logCreateDatabase(opCtx->getClient(), dbname);if (justCreated)*justCreated = true;}auto newDb = std::make_unique<DatabaseImpl>(dbname, ++_epoch);newDb->init(opCtx);// Finally replace our nullptr entry with the new Database pointer.removeDbGuard.dismiss();lk.lock();auto it = _dbs.find(dbname);// Dropping a database requires a MODE_X lock, so the entry in the `_dbs` map cannot disappear.invariant(it != _dbs.end());if (it->second) {// Creating databases only requires a DB lock in MODE_IX. Thus databases can concurrently// created. If this thread "lost the race", return the database object that was persisted in// the `_dbs` map.return it->second;}it->second = newDb.release();invariant(_getNamesWithConflictingCasing_inlock(dbname.toString()).empty());return it->second;
}

/mongo/db/catalog/database_impl.cpp中DatabaseImpl::init代码:

void DatabaseImpl::init(OperationContext* const opCtx) const {Status status = validateDBName(_name);if (!status.isOK()) {warning() << "tried to open invalid db: " << _name;uasserted(10028, status.toString());}auto& catalog = CollectionCatalog::get(opCtx);for (const auto& uuid : catalog.getAllCollectionUUIDsFromDb(_name)) {auto collection = catalog.lookupCollectionByUUID(uuid);invariant(collection);// If this is called from the repair path, the collection is already initialized.if (!collection->isInitialized())collection->init(opCtx);}// At construction time of the viewCatalog, the CollectionCatalog map wasn't initialized yet,// so no system.views collection would be found. Now that we're sufficiently initialized, reload// the viewCatalog to populate its in-memory state. If there are problems with the catalog// contents as might be caused by incorrect mongod versions or similar, they are found right// away.auto views = ViewCatalog::get(this);Status reloadStatus = views->reload(opCtx, ViewCatalogLookupBehavior::kValidateDurableViews);if (!reloadStatus.isOK()) {warning() << "Unable to parse views: " << redact(reloadStatus)<< "; remove any invalid views from the " << _viewsName<< " collection to restore server functionality." << startupWarningsLog;}
}

DatabaseImpl::init这段代码是 MongoDB 中DatabaseImpl类的init方法实现,主要功能是完成数据库的初始化工作,包括验证数据库名合法性、初始化集合以及加载视图目录等。

http://www.xdnf.cn/news/16974.html

相关文章:

  • HTTP GET 请求教程
  • 数据结构-单向链表
  • NDK-参数加密和签名校验
  • Linux(centos)安全狗
  • 线程互斥锁:守护临界区的关键
  • Mybatis 简单练习,自定义sql关联查询
  • 2025年信创政策解读:如何应对国产化替代挑战?(附禅道/飞书多维表格/华为云DevCloud实战指南)
  • 【C#】操作Execl和Word文件-1
  • 白杨SEO:百度搜索开放平台发布AI计划是什么?MCP网站红利来了?顺带说说其它
  • AWS Lambda Function 全解:无服务器计算
  • 如何使用 DBeaver 连接 MySQL 数据库
  • script标签放在header里和放在body底部里有什么区别?
  • Spring之【Bean的实例化方式】
  • Azure DevOps - 使用 Ansible 轻松配置 Azure DevOps 代理 - 第6部分
  • 设计模式(一)——抽象工厂模式
  • 机器学习实战:逻辑回归深度解析与欺诈检测评估指标详解(二)
  • 16.8 华为昇腾CANN架构深度实战:3大核心引擎解析与性能优化216%秘籍
  • 机器学习【六】readom forest
  • Dubbo 3.x源码(32)—Dubbo Provider处理服务调用请求源码
  • Ribbon 核心原理与架构详解:服务负载均衡的隐形支柱
  • 解决MySQL删除/var/lib/mysql下的所有文件后无法启动的问题
  • Flink从Kafka读取数据的完整指南
  • 段落注入(Passage Injection):让RAG系统在噪声中保持清醒的推理能力
  • 【动态规划 | 回文字串问题】动态规划解回文问题的核心套路
  • 基于落霞归雁思维框架的自动化测试实践与探索
  • 项目一:Python实现PDF增删改查编辑保存功能的全栈解决方案
  • 使用 SecureCRT 连接华为 eNSP 模拟器的方法
  • 浅谈 Python 中的 next() 函数 —— 迭代器的驱动引擎
  • 嵌入式开发学习———Linux环境下IO进程线程学习(三)
  • 【五大联赛】 2025-2026赛季基本信息