How can you specify the order of properties in a j

2019-01-15 06:12发布

问题:

The MongoDB documentation states:

For indexes with more than one key (i.e. compound indexes) the sequence of fields is important.

But ECMAScript defines an object as follows:

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.

When using MongoDB in node.js (for example by using this module), you're using server side javascript, like the example below.

How do you specify a sequence when MongoDB expects an object (AKA unordered collection of properties)?

collection.ensureIndex({
    date    : -1,
    client  : 1,
    product : 1
});

回答1:

In MongoDB, the order of fields in a document is indeed significant, and all language drivers provide a means of specifying documents that way, even if the underlying programming language does not have such a concept.

The document format that MongoDB uses in its shell is JSON-like but not strict JSON. Among other things, order of fields is always preserved.

In Javascript, the standard defines fields as unordered, so implementations are free to ignore/not preserve the ordering. But in practice, all implementations do preserve the ordering. In particular the V8 engine preserves the ordering, which is the engine used in node.js so it's no problem.