跳过返回结果
概述
在本指南中,您可以学习如何使用 MongoDB Rust 驱动程序执行读取操作,在返回结果时跳过指定数量的文档。
示例数据的样本数据
本指南中的示例使用以下内容Book
结构作为 books
集合中文档的模型
struct Book { name: String, author: String, length: i32, }
以下代码演示了如何将样本数据插入到 books
集合中
let uri = "connection string"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Book> = client.database("db").collection("books"); let books = vec![ Book { id: 1, name: "The Brothers Karamazov".to_string(), author: "Dostoyevsky".to_string(), length: 824, }, Book { id: 2, name: "Atlas Shrugged".to_string(), author: "Rand".to_string(), length: 1088, }, Book { id: 3, name: "Les Misérables".to_string(), author: "Hugo".to_string(), length: 1462, }, Book { id: 4, name: "A Dance with Dragons".to_string(), author: "Martin".to_string(), length: 1104, }, ]; my_coll.insert_many(books).await?;
跳过文档
您可以选择跳过查询检索到的结果,或者跳过聚合管道中的结果。
本节将描述以下几种跳过结果的方式
skip() 方法:将
skip()
方法链接到find()
方法FindOptions 结构体:使用
skip()
选项构建方法来配置FindOptions
结构体聚合管道:创建一个使用
$skip
阶段的管道
如果跳过的文档数量超过了查询匹配的文档数量,则该查询返回没有文档。
查找操作返回文档的自然顺序,不按任何字段排序。为了避免跳过随机文档,在设置跳过选项之前,使用 sort()
方法按具有唯一值的字段对文档进行排序。有关更多信息,请参阅排序结果指南。
skip() 方法示例
要跳过文档,您可以将 skip()
方法链接到 find()
方法。skip()
方法接受一个整数,指定从结果集开头跳过的文档数。
此示例执行一个 find()
操作,执行以下操作
按
author
字段值的升序排序结果跳过前两个文档
返回剩余的文档
let mut cursor = my_coll .find(doc! {}) .sort(doc! { "author": 1 }) .skip(2).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 } Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
选项示例
如果您正在设置和重用查询选项,可以使用FindOptions
。通过使用skip()
选项构建器方法来设置FindOptions
结构中的skip
字段。然后,将with_options()
方法链接到find()
方法,并将您的FindOptions
结构作为参数传递给with_options()
方法。
此示例执行一个 find()
操作,执行以下操作
按
name
字段值的降序排序结果跳过第一个文档
返回剩余的文档
let find_options = FindOptions::builder() .sort(doc! { "name": -1 }) .skip(1) .build(); let mut cursor = my_coll.find(doc! {}).with_options(find_options).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Book { name: "Les Misérables", author: "Hugo", length: 1462 } Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
聚合示例
您可以在聚合管道中使用$skip
阶段来跳过文档。有关聚合操作的更多信息,请参阅聚合指南。
此示例运行了一个执行以下操作的聚合管道
按
author
字段值的升序排序结果跳过第一个文档
返回剩余的文档
let pipeline = vec![ doc! { "$match": {} }, doc! { "$sort": { "author": 1 } }, doc! { "$skip": 1 }, ]; let mut cursor = my_coll.aggregate(pipeline).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Document({"_id": Int32(3), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)}) Document({"_id": Int32(4), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)}) Document({"_id": Int32(2), "name": String("Atlas Shrugged"), "author": String("Rand"), "length": Int32(1088)})
更多信息
有关本指南中提到的操作的更多信息,请参阅以下指南
API 文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下 API 文档