Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Go 驱动程序

跳过返回的结果

在此页面上

  • 概述
  • 跳过
  • 聚合(Aggregation)
  • 更多信息

在本指南中,您可以了解如何跳过读取操作中返回的指定数量的结果。

本部分的示例使用以下 Course 结构作为 courses 集合中文档的模型:

type Course struct {
Title string
Enrollment int32
}

要运行本指南中的示例,请使用如下代码段将这些文档加载到 db.courses 集合中:

coll := client.Database("db").Collection("courses")
docs := []interface{}{
Course{Title: "World Fiction", Enrollment: 35},
Course{Title: "Abstract Algebra", Enrollment: 60},
Course{Title: "Modern Poetry", Enrollment: 12},
Course{Title: "Plate Tectonics", Enrollment: 45},
}
result, err := coll.InsertMany(context.TODO(), docs)

提示

不存在的数据库和集合

如果执行写操作时不存在必要的数据库和集合,服务器会隐式创建这些数据库和集合。

每个文档都包含大学课程的说明,其中包括课程标题和最大注册人数,分别对应于titleenrollment字段。

要跳过查询返回的指定数量的结果,请将要跳过的文档数量传递给读取操作选项的SetSkip()方法。

以下读取操作将选项对象作为参数:

  • Find()

  • FindOne()

  • CountDocuments()

  • gridfs.Bucket.Find()

如果文档数量超过查询的匹配文档数量,则该查询不会返回任何文档。

提示

SetSkip()方法传递负数会导致运行时错误。

查找操作按存储顺序返回文档,未按任何字段排序。为避免跳过随机文档,请在设置跳过选项之前,使用SetSort()方法按具有唯一值的字段对文档进行排序。

以下示例通过以下行为执行 Find() 操作:

  • enrollment字段中按升序对结果进行排序

  • 跳过前两个文档

opts := options.Find().SetSort(bson.D{{"enrollment", 1}}).SetSkip(2)
cursor, err := coll.Find(context.TODO(), bson.D{}, opts)
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}

您还可以在聚合管道中包含 $skip阶段以跳过文档。

以下示例通过以下行为执行Aggregate()操作:

  • enrollment(注册)字段中按降序对结果进行排序

  • 跳过第一个文档

sortStage := bson.D{{"$sort", bson.D{{"enrollment", -1}}}}
skipStage := bson.D{{"$skip", 1}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage, skipStage})
if err != nil {
panic(err)
}
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}

要了解有关提到的操作的更多信息,请参阅以下指南:

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

← 对结果进行排序