“文档” 菜单
文档首页
/ / /
Node.js 驱动程序
/ / /

对结果进行排序

在此页面上

  • 概述
  • 示例文档
  • 例子

使用 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 }

当使用指定的排序时,两个或更多文档的顺序有时会不明确。在上例中,“A Dance with Dragons”和“Infinite Jest”都有 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 }
← 检索非重复值