如何在mongodb中维护排序属性的顺序? [英] How is order of properties maintained for sort in mongodb?

查看:111
本文介绍了如何在mongodb中维护排序属性的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题的答案,属性的顺序不保证对象。那么当我们将多个排序字段作为对象传递时,sort函数如何在MongoDB中完美地工作?

As per the answer to the question, the order of properties on an object is not guaranteed. Then how does the sort function work flawlessly in MongoDB when we pass multiple sort fields as an object?

db.users.find({}).sort({firstName: 1, age:-1}).exec(callback);

mongodb如何知道它首先必须按firstName排序,然后按年龄排序?这是错误的假设吗?

How does mongodb know that it first has to sort by firstName and then by age? Is it working on a wrong assumption?

推荐答案

这是一个有趣的问题。

它适用于大多数ECMAScript实现,实际上执行保留密钥顺序(例如,Node使用的V8)。但是,官方 Node MongoDB驱动程序确实不鼓励使用它,而是提供两种不同的符号:

It works as most ECMAScript implementations actually do preserve the key order (e.g. V8 which is used by Node). However, the official Node MongoDB driver does not encourage its use, instead it offers two different notations:


可以通过选项参数排序来获取排序,该排序采用数组
排序首选项

Sorting can be acieved with option parameter sort which takes an array of sort preferences

{   "sort": [['field1','asc'], ['field2','desc']] }

使用单个升序字段,可以使用字段名称替换数组。 / p>

With single ascending field the array can be replaced with the name of the field.

{   "sort": "name" }


Mongoose文档没有提到任何关于密钥顺序的信息(至少不是我所知道的)。但它也提供了两种不同的排序方法

The Mongoose documentation does not mention anything regarding key order (at least not that I know of). But it also offers two different approaches to sorting:


// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });

// equivalent
query.sort('field -test');


事实上似乎Mongoose排序功能是基于错误的(但目前是有效的)假设。在使用多个键进行排序时,最好使用字符串表示法。
直接使用MongoDB时(例如在MongoDB shell中)使用对象表示法排序正常,因为它不使用纯JSON但是扩展JSON

Indeed it seems that the Mongoose sort functionality was based on wrong (but currently valid) assumption. It is probably best if you use the string notation when sorting with multiple keys. Sorting with the object notation works properly when using MongoDB directly (e.g. in the MongoDB shell) as it does not use pure JSON but extended JSON.

另请参阅这个非常相关的问题:如何指定属性的顺序? node.js中MongoDB索引的javascript对象?

Also see this very related question: How can you specify the order of properties in a javascript object for a MongoDB index in node.js?

还有 Mongoose问题


是的,对于猫鼬和mongodb
司机来说,这是一个不幸的困境。 ECMAScript表示按键没有订购,但它们实际上是在V8中订购的
(数字键除外,这是一个令人讨厌的边缘
的情况),并且可能会继续在V8中为$ b订购$ b可预见的未来。 您可以使用[['field1','asc']]语法或
特定于mongoose的'field1 -field2'语法或ES2015 Map类
(保证键的插入顺序) )如果你关注
关键订单。

所以当使用Mongoose时,要么使用字符串符号或新添加的对 ES2015地图保证按插入订单排序。

So when using Mongoose, either use the string notation or the newly added support for ES2015 Maps which are guaranteed to be ordered by insertion order.

这篇关于如何在mongodb中维护排序属性的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆