定义
行为
使用 $skip 处理排序的结果
如果将 $skip 阶段与以下任何一项一起使用:
$sort聚合阶段,sort()方法,或findAndModify命令或findAndModify()shell 方法中的sort字段,
在将结果传递到 $skip 阶段之前,请务必在排序中至少包含一个包含唯一值的字段。
对包含重复值的字段进行排序时,可能会在多次执行中对这些重复字段返回不同的排序顺序,尤其是当集合正在接收写入时。
为确保排序一致,最简单方法是在排序查询中纳入 _id 字段。
点击以下链接,详细了解每项内容:
示例
本页上的C#示例使用Atlas示例数据集中的 sample_mflix数据库。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅MongoDB .NET/ C#驱动程序文档中的入门。
以下 Movie 类对 sample_mflix.movies 集合中的文档进行建模:
[] public class Movie { [] public ObjectId Id { get; set; } [] public string Title { get; set; } = null!; [] public int? Year { get; set; } [] public int? Runtime { get; set; } [] public string? Rated { get; set; } [] public int Metacritic { get; set; } [] public string? Plot { get; set; } [] public string? Type { get; set; } [] public string[]? Cast { get; set; } [] public string[]? Directors { get; set; } [] public string[]? Writers { get; set; } [] public ImdbData? Imdb { get; set; } }
要使用MongoDB .NET/C#驱动程序将 $skip 阶段添加到聚合管道,请对 PipelineDefinition对象调用 Skip() 方法。
以下示例创建了一个管道阶段,按标题和ID对电影进行排序,并跳过前 5 个文档:
var pipeline = new EmptyPipelineDefinition<Movie>() .Sort(Builders<Movie>.Sort .Ascending(m => m.Title) .Ascending(m => m.Id)) .Skip(5) .Limit(5);
{"_id": "...", "title": "'Doc'", "runtime": "...", "rated": "...", "year": "...", "metacritic": "..."} {"_id": "...", "title": "'Pimpernel' Smith", "runtime": "...", "rated": "...", "year": "...", "metacritic": "..."} {"_id": "...", "title": "'R Xmas", "runtime": "...", "rated": "...", "year": "...", "metacritic": "..."} {"_id": "...", "title": "'Round Midnight", "runtime": "...", "rated": "...", "year": "...", "metacritic": "..."} {"_id": "...", "title": "'Til Madness Do Us Part", "runtime": "...", "rated": "...", "year": "...", "metacritic": "..."}
要使用MongoDB Node.js驱动程序将 $skip 阶段添加到聚合管道,请在管道对象中使用 $skip操作符。
以下示例创建了一个管道阶段,该阶段跳过输入集合中的前五个文档,并将剩余文档传递到管道的下一个阶段。然后,示例运行聚合管道:
const pipeline = [{ $skip: 5 }]; const cursor = collection.aggregate(pipeline); return cursor;