Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

$skip(聚合阶段)

$skip

跳过进入该阶段的指定数量的 文档,并将剩余的文档传递到管道的下一阶段。

$skip 阶段具有以下原型形式:

{ $skip: <positive 64-bit integer> }

$skip 取一个正整数,用于指定跳过的最大文档数量。

注意

从 MongoDB 5.0 开始,$skip 管道聚合有 64 位整数限制。传递给管道的值如果超过此限制,将返回无效参数错误。

如果将 $skip 阶段与以下任何一项一起使用:

  • $sort 聚合阶段,

  • sort() 方法,或

  • findAndModify 命令或 findAndModify() shell 方法中的 sort 字段,

在将结果传递到 $skip 阶段之前,请务必在排序中至少包含一个包含唯一值的字段。

对包含重复值的字段进行排序时,可能会在多次执行中对这些重复字段返回不同的排序顺序,尤其是当集合正在接收写入时。

为确保排序一致,最简单方法是在排序查询中纳入 _id 字段。

点击以下链接,详细了解每项内容:

考虑以下示例:

db.article.aggregate([
{ $skip : 5 }
]);

此操作跳过管道传递给它的前 5 个文档。$skip 对其沿管道传递的文档内容没有影响。

本页上的C#示例使用Atlas示例数据集中的 sample_mflix数据库。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅MongoDB .NET/ C#驱动程序文档中的入门

以下 Movie 类对 sample_mflix.movies 集合中的文档进行建模:

[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string Title { get; set; } = null!;
[BsonElement("year")]
public int? Year { get; set; }
[BsonElement("runtime")]
public int? Runtime { get; set; }
[BsonElement("rated")]
public string? Rated { get; set; }
[BsonElement("metacritic")]
public int Metacritic { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("type")]
public string? Type { get; set; }
[BsonElement("cast")]
public string[]? Cast { get; set; }
[BsonElement("directors")]
public string[]? Directors { get; set; }
[BsonElement("writers")]
public string[]? Writers { get; set; }
[BsonElement("imdb")]
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;

要查看使用 $skip 阶段的完整聚合示例,请参阅完整聚合管道教程

后退

$shardedDataDistribution

在此页面上