mongodb源代碼分析createCollection命令由create.idl變成create_gen.cpp過程

mongodb命令db.createCollection(name, options)創建一個新集合。由于 MongoDB 在命令中首次引用集合時會隱式創建集合,因此此方法主要用于創建使用特定選項的新集合。

例如,您使用db.createCollection()創建:固定大小集合;集群化集合;使用模式驗證的新集合。

db.createCollection()?方法具有以下原型形式:

db.createCollection( <name>,{capped: <boolean>,timeseries: {                  // Added in MongoDB 5.0timeField: <string>,        // required for time series collectionsmetaField: <string>,granularity: <string>,bucketMaxSpanSeconds: <number>,  // Added in MongoDB 6.3bucketRoundingSeconds: <number>  // Added in MongoDB 6.3},expireAfterSeconds: <number>,clusteredIndex: <document>,  // Added in MongoDB 5.3changeStreamPreAndPostImages: <document>,  // Added in MongoDB 6.0size: <number>,max: <number>,storageEngine: <document>,validator: <document>,validationLevel: <string>,validationAction: <string>,indexOptionDefaults: <document>,viewOn: <string>,pipeline: <pipeline>,collation: <document>,writeConcern: <document>})

db.createCollection()參數解釋:

參數類型說明
cappedBoolean是否為固定大小集合(默認false
sizeNumber固定集合的最大大小(字節),僅在capped=true時有效
maxNumber固定集合的最大文檔數量
validatorDocumentJSON Schema 驗證器,確保文檔符合特定格式
storageEngineDocument存儲引擎特定配置(如 WiredTiger 參數)
indexesArray創建集合時預定義的索引
writeConcernDocument默認寫關注級別
readConcernDocument默認讀關注級別
autoIndexIdBoolean是否自動為_id字段創建索引(默認true
viewOnString創建視圖時指定源集合
pipelineArray視圖的聚合管道
collationDocument指定排序規則(如區分大小寫)
timeseriesDocument時間序列集合配置
expireAfterSecondsNumberTTL 索引,指定文檔自動過期時間(秒)

mongodb源代碼src\mongo\db\commands文件夾下面是命令文件所在地:

count_cmd.cpp封裝count命令,distinct.cpp封裝了distinct命令,dbcommands.cpp封裝了CmdCreate和CmdDrop、CmdDatasize等。CmdCreate封裝了創建collection過程。CreateCommand解析create命令,重點是CreateCommand怎么來的?工具跟蹤進去是create_gen.cpp。create_gen.cpp原來是create.idl。

/* create collection */
class CmdCreate : public BasicCommand {
public:CmdCreate() : BasicCommand("create") {}virtual bool run(OperationContext* opCtx,const string& dbname,const BSONObj& cmdObj,BSONObjBuilder& result) {IDLParserErrorContext ctx("create");CreateCommand cmd = CreateCommand::parse(ctx, cmdObj);...}
} cmdCreate;

create.idlidl文件是什么?

MongoDB 采用 IDL(接口定義語言)生成 C++ 代碼是一種常見的工程實踐,減少樣板代碼,提高開發效率,避免手動編寫重復邏輯(如字段提取、類型檢查、錯誤處理),確保代碼一致性(所有命令遵循相同的驗證規則)。

mongo\db\commands\create.idl內容是:

global:cpp_namespace: "mongo"imports:- "mongo/idl/basic_types.idl"commands:create:description: "Parser for the 'create' Command"namespace: concatenate_with_dbcpp_name: CreateCommandstrict: truefields:capped:description: "Specify true to create a capped collection. If you specify true, youmust also set a maximum size in the 'size' field."type: safeBooldefault: falseautoIndexId:description: "Specify false to disable the automatic creation of an index on the_id field."type: safeBooloptional: trueidIndex:description: "Specify the default _id index specification."type: objectoptional: truesize:...

create.idl怎么轉換成create.cpp的呢?

在 buildscripts 有一個目錄 idl,這里負責根據 src 中的 idl 生成文件。其中主要看buildscripts/idl/idl/generator.py文件,根據cpp_name生成對應的cpp文件,其中有一段邏輯:

def generate(self, spec):# type: (ast.IDLAST) -> None...spec_and_structs = spec.structsspec_and_structs += spec.commandsfor struct in spec_and_structs:self.gen_description_comment(struct.description)with self.gen_class_declaration_block(struct.cpp_name):self.write_unindented_line('public:')# Generate a sorted list of string constantsself.gen_string_constants_declarations(struct)self.write_empty_line()# Write constructorself.gen_class_constructors(struct)self.write_empty_line()# Write serializationself.gen_serializer_methods(struct)if isinstance(struct, ast.Command):self.gen_op_msg_request_methods(struct)# Write getters & settersfor field in struct.fields:if not field.ignore:if field.description:self.gen_description_comment(field.description)self.gen_getter(struct, field)if not struct.immutable and not field.chained_struct_field:self.gen_setter(field)if struct.generate_comparison_operators:self.gen_comparison_operators_declarations(struct)self.write_unindented_line('protected:')self.gen_protected_serializer_methods(struct)# Write private validatorsif [field for field in struct.fields if field.validator]:self.write_unindented_line('private:')for field in struct.fields:if not field.ignore and not struct.immutable and \not field.chained_struct_field and field.validator:self.gen_validators(field)self.write_unindented_line('private:')# Write command member variablesif isinstance(struct, ast.Command):self.gen_known_fields_declaration()self.write_empty_line()self.gen_op_msg_request_member(struct)# Write member variablesfor field in struct.fields:if not field.ignore and not field.chained_struct_field:self.gen_member(field)# Write serializer member variables# Note: we write these out second to ensure the bit fields can be packed by# the compiler.for field in struct.fields:if _is_required_serializer_field(field):self.gen_serializer_member(field)self.write_empty_line()for scp in spec.server_parameters:if scp.cpp_class is None:self._gen_exported_constexpr(scp.name, 'Default', scp.default, scp.condition)self._gen_extern_declaration(scp.cpp_vartype, scp.cpp_varname, scp.condition)self.gen_server_parameter_class(scp)if spec.configs:for opt in spec.configs:self._gen_exported_constexpr(opt.name, 'Default', opt.default, opt.condition)self._gen_extern_declaration(opt.cpp_vartype, opt.cpp_varname, opt.condition)self._gen_config_function_declaration(spec)

buildscripts/idl/idl/generator.py運行之后,python運行結果在對應的文件夾\build\opt\mongo\db\commands

create.idl生成了create_gen.h和create_gen.cpp,C++編譯之后create_gen.obj文件。

\build\opt\mongo\db\commands\create_gen.h,createCollection命令中的各個參數在下面文件都能看到,參數的get和set方法,代碼:

namespace mongo {/*** Parser for the 'create' Command*/
class CreateCommand {
public:...explicit CreateCommand(const NamespaceString nss);static CreateCommand parse(const IDLParserErrorContext& ctxt, const BSONObj& bsonObject);static CreateCommand parse(const IDLParserErrorContext& ctxt, const OpMsgRequest& request);void serialize(const BSONObj& commandPassthroughFields, BSONObjBuilder* builder) const;OpMsgRequest serialize(const BSONObj& commandPassthroughFields) const;BSONObj toBSON(const BSONObj& commandPassthroughFields) const;const NamespaceString& getNamespace() const { return _nss; }bool getCapped() const { return _capped; }void setCapped(bool value) & {  _capped = std::move(value);  }const boost::optional<bool> getAutoIndexId() const& { return _autoIndexId; }void getAutoIndexId() && = delete;void setAutoIndexId(boost::optional<bool> value) & {  _autoIndexId = std::move(value);  }
...

\build\opt\mongo\db\commands\create_gen.cpp,CreateCommand解析方法,createCollection命令解析成CreateCommand對象,代碼:

namespace mongo {...
CreateCommand::CreateCommand(const NamespaceString nss) : _nss(std::move(nss)), _dbName(nss.db().toString()), _hasDbName(true) {// Used for initialization only
}CreateCommand CreateCommand::parse(const IDLParserErrorContext& ctxt, const BSONObj& bsonObject) {NamespaceString localNS;CreateCommand object(localNS);object.parseProtected(ctxt, bsonObject);return object;
}CreateCommand CreateCommand::parse(const IDLParserErrorContext& ctxt, const OpMsgRequest& request) {NamespaceString localNS;CreateCommand object(localNS);object.parseProtected(ctxt, request);return object;
}

總結:buildscripts/idl/idl/generator.py把create.idl轉成create_gen.cpp和create_gen.h,再編譯成create_gen.obj,CreateCommand對象封裝命令createCollection。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/94150.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/94150.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/94150.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

達夢(DM8)常用管理SQL命令(3)

達夢(DM8)常用管理SQL命令(3) 1.表空間 -- 查看表空間信息 SQL> SELECT * FROM v$tablespace;-- 查看數據文件 SQL> SELECT * FROM v$datafile;-- 表空間使用情況 SQL> SELECT df.tablespace_name "表空間名稱",df.bytes/1024/1024 "總大小(MB)&q…

【Django】-5- ORM的其他用法

一、&#x1f680; ORM 新增數據魔法&#xff01;核心目標教你用 Django ORM 給數據庫 新增數據 &#xff01;就像給數據庫 “生小數據寶寶”&#x1f476;方法 1&#xff1a;實例化 Model save&#xff08;一步步喂數據&#xff09;obj Feedback() # 實例化 obj.quality d…

Flink Checkpoint機制:大數據流處理的堅固護盾

引言在大數據技術蓬勃發展的當下&#xff0c;數據處理框架層出不窮&#xff0c;Flink 憑借其卓越的流批一體化處理能力&#xff0c;在大數據流處理領域占據了舉足輕重的地位 。它以高吞吐量、低延遲和精準的一次性語義等特性&#xff0c;成為眾多企業處理實時數據的首選工具。在…

【STM32-HAL】 SPI通信與Flash數據寫入實戰

文章目錄1.參考教程2. 4種時間模式3. 3個編程接口3.1 HAL_StatusTypeDef HAL_SPI_Transmit(...) &#xff1a;3.1.1 參數說明3.1.2 例子3.2 HAL_StatusTypeDef HAL_SPI_Receive(...) &#xff1a;3.2.1參數說明3.2.2 例子3.3 HAL_StatusTypeDef HAL_SPI_TransmitReceive(...) &…

SNR-Aware Low-light Image Enhancement 論文閱讀

信噪比感知的低光照圖像增強 摘要 本文提出了一種新的低光照圖像增強解決方案&#xff0c;通過聯合利用信噪比&#xff08;SNR&#xff09;感知的變換器&#xff08;transformer&#xff09;和卷積模型&#xff0c;以空間變化的操作方式動態增強像素。對于極低信噪比&#xff0…

在 Vue3 中使用 Mammoth.js(在 Web 應用中預覽 Word 文檔)的詳解、常見場景、常見問題及最佳解決方案的綜合指南

一、Mammoth.js 簡介與核心功能 Mammoth.js 是一個專用于將 .docx 文檔轉換為 HTML 的庫,適用于在 Web 應用中預覽 Word 文檔。其核心特點包括: 語義化轉換:基于文檔樣式(如標題、段落)生成簡潔的 HTML 結構,忽略復雜樣式(如居中、首行縮進)。 輕量高效:適用于需要快…

2025 年 VSCode 插件離線下載硬核攻略

微軟 2025 年起關閉 VSCode 官方市場 .vsix 文件直接下載入口&#xff0c;給企業內網開發者帶來極大不便。不過別擔心,今天提供一個下載.vsix文件地址。 VSC插件下載 (dreamsoul.cn) 下載好的.vsix文件后&#xff0c;打開vscode的應用&#xff0c;選擇右上角...打開&#xff…

[leetcode] 位運算

位運算這類題目奇思妙招很多&#xff0c;優化方法更是非常考驗經驗積累。 常用小技能&#xff1a; bit_count()&#xff1a;返回整數的二進制表示中1的個數&#xff0c;e.g. x 7 x.bit_count() # 32.bit_length()&#xff1a;返回整數的二進制表示的長度&#xff0c;e.g. …

關于assert()函數,eval()函數,include

一.assert()函數例子assert("strpos($file, ..) false") or die("Detected hacking attempt!");assert("file_exists($file)") or die("That file doesnt exist!");第一個是會檢驗$file是否有.. &#xff0c;如果有strpos會返回true&…

ICT模擬零件測試方法--電位器測試

ICT模擬零件測試方法–電位器測試 文章目錄ICT模擬零件測試方法--電位器測試電位器測試電位器測試配置電位器測試配置電位器測試注意事項電位器測量選項電位器測試 電位器測試測量從 0.1 歐姆到 10M 歐姆的電阻。 本節介紹&#xff1a; 電位器測試配置電位器測試注意事項電位…

wsl2使用宿主機網絡方法

在Windows的資源管理器的地址欄輸入&#xff1a; %UserProfile% &#xff0c;即可打開當前用戶的主目錄&#xff0c;創建文件&#xff1a; .wslconfig 輸入[experimental]networkingModemirroredautoProxytrue之后重啟WSL 管理員身份運行PowerShell&#xff1a; 停止WSL&#x…

當Windows遠程桌面出現“身份驗證錯誤。要求的函數不受支持”的問題

當Windows遠程桌面出現“身份驗證錯誤。要求的函數不受支持”的問題時&#xff0c;可以參考以下方法解決&#xff1a;修改組策略設置適用于Windows專業版、企業版等有組策略編輯器的系統。1. 按下WinR組合鍵&#xff0c;輸入“gpedit.msc”&#xff0c;打開本地組策略編輯器。2…

零售新范式:開源AI大模型、AI智能名片與S2B2C商城小程序源碼驅動下的圈層滲透革命

摘要&#xff1a;在消費圈層化與渠道碎片化的雙重沖擊下&#xff0c;傳統零售渠道的"廣撒網"模式逐漸失效。阿里巴巴零售通、京東新通路、國美Plus等零售巨頭通過技術賦能重構小店生態&#xff0c;但其本質仍停留于供應鏈效率提升層面。本文創新性提出"開源AI大…

電池自動生產線:科技賦能下的高效制造新范式

在當今科技飛速發展的時代&#xff0c;電池作為眾多電子設備和新能源產業的核心部件&#xff0c;其生產效率與質量至關重要。電池自動生產線的出現&#xff0c;猶如一場及時雨&#xff0c;為電池制造行業帶來了全新的變革與發展機遇。自動化流程&#xff0c;開啟高效生產之門傳…

CS224n:Word Vectors and Word Senses(二)

目錄 一、共現矩陣 1.1 基于共現矩陣的詞向量 二、SVD分解 2.1 基于共現矩陣的詞向量 vs. Word2Vec詞向量 三、GloVe詞向量 3.1 GloVe詞向量的好處 3.2 GloVe的一些結果展示 部分筆記來源參考 Beyond Tokens - 知乎 (zhihu.com) NLP教程(1) - 詞向量、SVD分解與Word2V…

I Built an Offline-Capable App by Myself: React Native Frontend, C# Backend

This isn’t a story about gluing together a few UI components. It’s about how I, as a solo developer, built a complete mobile application that works offline, syncs data automatically when online, and shares a unified backend with a web-based admin panel. …

在Idea中,配置maven

? 哈嘍&#xff0c;屏幕前的每一位開發者朋友&#xff0c;你們好呀&#xff01;?? 當你點開這篇文章時&#xff0c;或許正對著 IDE 里閃爍的光標發呆&#xff0c;或許剛解決一個卡了三天的 bug&#xff0c;正端著咖啡松口氣 —— 不管此刻的你在經歷什么&#xff0c;都想先和…

mac 字體遍歷demo

文章目錄邏輯字體類頭文件實現文件使用文件主程序CMakeLists文件腳本文件邏輯字體類 #ifndef LOGICAL_FONT_H #define LOGICAL_FONT_H#include <string> #include <memory> #include <CoreText/CoreText.h> #include <CoreFoundation/CoreFoundation.h&g…

2025牛客多校第六場 D.漂亮矩陣 K.最大gcd C.棧 L.最小括號串 個人題解

L.最小括號串 #數組操作 #貪心 題目 思路 感謝Leratiomyces大佬賽時的提示&#xff0c;否則估計還一直簽不了到&#xff08;&#xff09; 首先&#xff0c;貪心地構造出最優情況&#xff1a;數組左半部分全是(&#xff0c;右半部分全是)&#xff0c;隨后通過判斷給定的區間…

Ubuntu搭建PX4無人機仿真環境(5) —— 仿真環境搭建(以Ubuntu 22.04,ROS2 Humble 為例)

目錄前言1. 準備下載源碼方式一&#xff1a;方式二&#xff1a;安裝依賴安裝 Gazebo2. 安裝 Micro XRCE-DDS Agent3. 編譯4. 通信5. offboard 測試參考前言 本教程基于 ROS2 &#xff0c;在搭建之前&#xff0c;需要把 ROS2、QGC 等基礎環境安裝配置完成。但是這塊的資料相比較…