【问题标题】:Mongo compound index ordering [duplicate]Mongo复合索引排序[重复]
【发布时间】:2015-04-17 10:03:01
【问题描述】:

定义复合索引:

db.collection.ensureIndex( { orderDate: 1, zipcode: -1 } )

我突然恍然大悟:JS 对象的字段是有序的吗? 是否有一个隐含的假设,即 orderDate 是第一位的?我很惊讶它没有使用数组。

对于猫鼬,我们使用:

schema.index({a:1, b:1})

我们如何确保这个对象按照代码中指定的顺序传输到 mongo 服务器?

这篇文章说字段没有排序。 Does JavaScript Guarantee Object Property Order?

Is it acceptable style for Node.js libraries to rely on object key order?

【问题讨论】:

    标签: javascript node.js mongodb indexing


    【解决方案1】:

    来自documentation

    索引以升序 (1) 或降序 (-1) 排序顺序存储对字段的引用。对于单字段索引,键的排序顺序无关紧要,因为 MongoDB 可以在任一方向遍历索引。但是,对于复合索引,排序顺序对于确定索引是否支持排序操作很重要。

    因此,如果您使用

    创建索引
    db.collection.ensureIndex( { orderDate: 1, zipcode: -1 } ) 
    

    对象将被传输到 mongo 服务器,其中的字段按顺序排列,还请注意使用

    db.collection.ensureIndex( { orderDate: 1, zipcode: -1 } ) 
    

    db.collection.ensureIndex( {  zipcode: -1 , orderDate: 1} ) 
    

    将创建两个不同的复合索引

    【讨论】:

    • @Lucas 是的,订单有保证。这不是一个脆弱的假设。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2017-11-01
    • 2012-05-21
    相关资源
    最近更新 更多