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 等基础环境安装配置完成。但是这块的资料相比较…