0

To define a compound index:

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

It suddenly dawned on me : are the fields of a JS object ordered? Is there an implicit assumption that orderDate comes first? I'm quite surprised it doesn't use an array instead.

For mongoose, we use :

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

How can we ensure this object is transmitted to the mongo server with the fields ordered as specified in the code?

This post says fields are not ordered. Does JavaScript Guarantee Object Property Order?

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

Community
  • 1
  • 1

1 Answers1

1

From the documentation

Indexes store references to fields in either ascending (1) or descending (-1) sort order. For single-field indexes, the sort order of keys doesn’t matter because MongoDB can traverse the index in either direction. However, for compound indexes, sort order can matter in determining whether the index can support a sort operation.

So if you created your index using

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

the object will be transmitted to the mongo server with the fields as ordered also note that using

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

and

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

will create two different compound indexes

Community
  • 1
  • 1
styvane
  • 59,869
  • 19
  • 150
  • 156