排序结果
概述
用法sort
用于改变读取操作返回文档的顺序。Sort
指示MongoDB根据一个或多个字段的值以特定方向对返回的文档进行排序。要按字段以升序(最低优先)排序返回的文档,使用值1
。要按降序(最高优先)排序,则使用-1
。如果您未指定排序,MongoDB不保证查询结果的顺序。
示例文档
按照以下示例中的说明,将数据插入到myDB.books
集合中,并对查询结果进行排序。考虑一个包含描述书籍的文档的集合。要将此数据插入到集合中,请运行以下操作
const myDB = client.db("myDB"); const myColl = myDB.collection("books"); await myColl.insertMany([ { "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }, { "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 }, { "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 }, { "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 }, { "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 }, { "_id": 6, "name": "A Dance with Dragons", "author": "Martin", "length": 1104 }, ]);
注意
您的查询操作可能会返回一个包含匹配文档的游标引用。要了解如何检查游标中存储的数据,请参阅游标基础页面.
示例
将以下排序文档传递给读取操作,以确保操作首先返回长度较长的书籍,然后是长度较短的书籍
// define an empty query document const query = {}; // sort in descending (-1) order by length const sort = { length: -1 }; const cursor = myColl.find(query).sort(sort); for await (const doc of cursor) { console.dir(doc); }
在这种情况下,数字 -1
告诉读取操作按长度降序排序书籍。当使用空查询与 find()
一起使用此排序时,返回以下文档
{ "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 } { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 } { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }
有时,使用指定的排序,两个或多个文档的顺序是模糊的。在上面的例子中,“权力的游戏”和“无尽的玩笑”都有 1104
页,因此它们返回的顺序没有保证。为了以可重复的方式解决排序结果中的平局,请向排序文档中添加更多字段
// define an empty query document const query = {}; // sort in ascending (1) order by length const sort = { length: 1, author: 1 }; const cursor = myColl.find(query).sort(sort); for await (const doc of cursor) { console.dir(doc); }
将 author
字段添加到排序文档后,读取操作首先按 length
排序匹配的文档,如果有平局,则按 author
排序。匹配的文档字段按与排序文档中指定的顺序相同的顺序进行比较。find()
在使用此排序对与查询匹配的文档进行排序时返回以下文档顺序,在长度相同的两本书中,先返回 "Martin"
,然后返回 "Wallace"
{ "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 } { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 } { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 } { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 } { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 } { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }