Overview
在本指南中,您可以学习;了解如何使用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结构体
如果跳过的文档数超过查询的匹配文档数,则该查询不返回任何文档。
查找操作按自然顺序返回文档,未按任何字段进行排序。 为避免跳过随机文档,请在设置跳过选项之前,使用 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 文档: