返された結果をスキップする
Overview
このガイドでは、読み取り操作から返された指定された数の結果をスキップする方法を学習できます。
サンプル データ
To run the example in this guide, load these documents into the
tea.ratings
collection with the following
snippet:
coll := client.Database("tea").Collection("ratings") docs := []interface{}{ bson.D{{"type", "Masala"}, {"rating", 10}}, bson.D{{"type", "Assam"}, {"rating", 5}}, bson.D{{"type", "Oolong"}, {"rating", 7}}, bson.D{{"type", "Earl Grey"}, {"rating", 8}}, bson.D{{"type", "English Breakfast"}, {"rating", 5}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
存在しないデータベースとコレクション
書き込み操作を実行するときに必要なデータベースとコレクションが存在しない場合は、サーバーが暗黙的にそれらを作成します。
各ドキュメントには、 フィールドとtype
rating
フィールドに対応するお茶の種類の評価が含まれています。
注意
各例ではObjectID
値が切り捨てられます。この値はドライバーが個別に生成するためです。
スキップ
クエリから返された結果の指定した数をスキップするには、スキップするドキュメント数を読み取り操作のオプションのSetSkip()
メソッドに渡します。
次の読み取り操作メソッドの最後のパラメーターとしてオプションを指定します。
Find()
FindOne()
CountDocuments()
gridfs.Bucket.Find()
ドキュメントの数がクエリに一致するドキュメントの数を超える場合、そのクエリはドキュメントを返しません。
Tip
SetSkip()
メソッドに負の数を渡すと、ランタイム エラーが発生します。
Documents return in a natural order, which can lead to skipping random
documents. To avoid this, use a SetSort()
method before the
SetSkip()
method.
例
The following example performs the following actions in order with the
Find()
method:
An ascedning sort on the
rating
field最初の 2 つのドキュメントをスキップします
filter := bson.D{} opts := options.Find().SetSort(bson.D{{"rating", 1}}).SetSkip(2) cursor, err := coll.Find(context.TODO(), filter, opts) var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
集計
You can also include the $skip stage to specify a skip in an aggregation pipeline.
例
The following example performs the following actions in order with the
Aggregate()
method:
rating
フィールドでの降順の並べ替えSkips the first three documents
sortStage := bson.D{{"$sort", bson.D{{"rating", -1}}}} skipStage := bson.D{{"$skip", 3}} cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage, skipStage}) if err != nil { panic(err) } var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
詳細情報
上記で説明されている操作の詳細については、次のガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。