Mongoose 复合索引创建字段顺序
Mongoose compound index creation fields order
我对 mongodb 中的复合索引创建有疑问:
假设我要创建这个复合索引:
cSchema.index({account:1, authorization: 1, c_type: 1});
问题是,javascript 不能保证字典顺序,所以我不确定复合索引是否符合我的要求。
我如何确定它确实是 {account:1, authorization:1, c_type:1}
的顺序?
谢谢!
简单的答案是,大多数滥用不解析为对象上的整数的简单字符串属性将按创建顺序枚举的行为。虽然 not guaranteed in ES2015 for some enumeration methods,但它确实可以在像 Node/V8 这样的密闭环境中工作。这在大多数 JS 引擎中已经工作了一段时间,但在 ES2015 之前从未成为 ES 规范的一部分。
MongoDB
底层 MongoDB 驱动程序 createIndex
function supports String
, Array
and Object
index definitions. The parsing code is in a util function called parseIndexOptions
。
如果您指定一个字符串数组、数组对或对象,那么顺序将是固定的:
['location','type']
[['location', '2d'],['type', 1]]
[{location: '2d'},{type: 1}]
另请注意,createIndex
代码在获取 Object
索引属性时确实使用 Object.keys
进行枚举。
猫鼬
Schema#index
函数被记录为需要将对象传递给 "MongoDB driver's createIndex()
function",因此看起来支持传递您提供的任何选项。
虽然有几个地方需要进一步处理索引。例如,当您创建一个带有索引的子文档时,索引 needs to have the parent schema prefixed onto field names。快速浏览一下,我认为这段代码仍然适用于数组,但我在 Mongoose 代码中看不到任何测试,所以你可能想自己确认一下。
Mongoose 确实有一个 compound index test that relies on Object property order。
我对 mongodb 中的复合索引创建有疑问: 假设我要创建这个复合索引:
cSchema.index({account:1, authorization: 1, c_type: 1});
问题是,javascript 不能保证字典顺序,所以我不确定复合索引是否符合我的要求。
我如何确定它确实是 {account:1, authorization:1, c_type:1}
的顺序?
谢谢!
简单的答案是,大多数滥用不解析为对象上的整数的简单字符串属性将按创建顺序枚举的行为。虽然 not guaranteed in ES2015 for some enumeration methods,但它确实可以在像 Node/V8 这样的密闭环境中工作。这在大多数 JS 引擎中已经工作了一段时间,但在 ES2015 之前从未成为 ES 规范的一部分。
MongoDB
底层 MongoDB 驱动程序 createIndex
function supports String
, Array
and Object
index definitions. The parsing code is in a util function called parseIndexOptions
。
如果您指定一个字符串数组、数组对或对象,那么顺序将是固定的:
['location','type']
[['location', '2d'],['type', 1]]
[{location: '2d'},{type: 1}]
另请注意,createIndex
代码在获取 Object
索引属性时确实使用 Object.keys
进行枚举。
猫鼬
Schema#index
函数被记录为需要将对象传递给 "MongoDB driver's createIndex()
function",因此看起来支持传递您提供的任何选项。
虽然有几个地方需要进一步处理索引。例如,当您创建一个带有索引的子文档时,索引 needs to have the parent schema prefixed onto field names。快速浏览一下,我认为这段代码仍然适用于数组,但我在 Mongoose 代码中看不到任何测试,所以你可能想自己确认一下。
Mongoose 确实有一个 compound index test that relies on Object property order。