ECMAScript defines JavaScript objects as an unordered collection of properties .
However, the MongoDB $sort
operator in the aggregation pipeline specifies documents will be sorted in the order the properties are listed on the $sort
property .
db.users.aggregate(
[{ $sort : { age : -1, posts: 1 } }]
);
This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.
Does MongoDB have a different definition for javascript objects since apparently MongoDB depends on property order?
Does MongoDB have a different definition for javascript objects since apparently MongoDB depends on property order?
MongoDB's server-side document representation is a JSON-like binary format called BSON , which has richer types than JavaScript/JSON and preserves field order. MongoDB sorts server-side queries (eg. find().sort()
or aggregation's $sort
stage) using BSON Comparison/Sort Order .
When you interact with MongoDB through the mongo
shell or a driver, the communication to the MongoDB server is using the MongoDB Wire Protocol with messages encapsulated in BSON. It is the driver and application author's responsibility to ensure object representations use an order-preserving data structure where required. This is typically an ordered hash/map/dictionary depending on the language implementation and common terminology.
You should check your driver documentation for any specific suggestions. For example, PyMongo (the official Python driver) provides a SON
subclass of the standard Python dict
that maintains ordering of keys and provides some extra helpers for mapping Python types to BSON.
Modern JavaScript engines do tend to maintain an implicit ordering (insertion order of fields in objects) but there are objects such as Map that can be used when an explicit guarantee is required. In the specific example of the mongo
shell, the behaviour of the integrated JavaScript engine is expected to be order-preserving.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.