Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you specify the order of properties in a javascript object for a MongoDB index in node.js?

Tags:

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
});
like image 584
Redsandro Avatar asked Aug 29 '13 14:08

Redsandro


People also ask

Does order of properties in object matter in JavaScript?

YES (but not always insertion order). Most Browsers iterate object properties as: Integer keys in ascending order (and strings like "1" that parse as ints) String keys, in insertion order (ES2015 guarantees this and all browsers comply) Symbol names, in insertion order (ES2015 guarantees this and all browsers comply)

Can MongoDB manipulate JavaScript objects?

The MongoDB shell is an interactive JavaScript shell. As such, it provides the capability to use JavaScript code directly in the shell or executed as a standalone JavaScript file.

What is indexing with respect to Nodejs and MongoDB?

Overview. Indexes are data structures that support the efficient execution of queries in MongoDB. They contain copies of parts of the data in documents to make queries more efficient. Without indexes, MongoDB must scan every document in a collection to find the documents that match each query.


1 Answers

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.

like image 62
drmirror Avatar answered Sep 27 '22 20:09

drmirror