【问题标题】:Mongoose compound index creation fields orderMongoose 复合索引创建字段顺序
【发布时间】:2017-09-04 15:21:32
【问题描述】:

我有一个关于在 mongodb 中创建复合索引的问题: 假设我想创建这个复合索引:

cSchema.index({account:1, authorization: 1, c_type: 1});

问题是,javascript 不保证字典顺序,所以我不能确定复合索引是否符合我想要的顺序。

我怎样才能确保它确实是 {account:1, authorization:1, c_type:1} 在那个顺序?

谢谢!

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    简单的答案是,大多数人滥用不解析为 Object 上的整数的简单 String 属性将按创建顺序枚举的行为。虽然not guaranteed in ES2015 for some enumeration methods,但它确实可以在像 Node/V8 这样的受限环境中工作。这已经在大多数 JS 引擎中工作了一段时间,但在 ES2015 之前从未成为 ES 规范的一部分。

    MongoDB

    底层 MongoDB 驱动程序createIndex 函数支持StringArrayObject 索引定义。解析代码在一个名为 parseIndexOptions 的 util 函数中。

    如果您指定字符串、数组对或对象的数组,则顺序将是固定的:

    ['location','type']
    [['location', '2d'],['type', 1]]
    [{location: '2d'},{type: 1}]
    

    还请注意,createIndex 代码在获取索引属性的Object 时确实使用Object.keys 进行枚举。

    猫鼬

    Schema#index 函数被记录为需要一个对象传递给“MongoDB 驱动程序的createIndex() 函数”,因此看起来支持传递您提供的任何选项。

    不过,有几个地方会进一步处理索引。例如,当您创建带有索引的子文档时,索引为needs to have the parent schema prefixed onto field names。快速浏览一下,我认为这段代码仍然适用于数组,但我在 Mongoose 代码中看不到任何测试,因此您可能需要自己确认。

    Mongoose 确实有一个compound index test that relies on Object property order

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多