Mongo复合索引排序

时间:2015-02-16 19:41:45

标签: javascript node.js mongodb indexing

定义复合索引:

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?

1 个答案:

答案 0 :(得分: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} ) 

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

相关问题