Sort Results — Go
Docs Menu

Docs HomeGo

結果を並べ替える

In this guide, you can learn how to specify the order of your results from read operations.

このガイドの例を実行するには、次のスニペットを使用してこれらのドキュメントをtea.ratingsコレクションにロードします。

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値が切り捨てられます。この値はドライバーが個別に生成するためです。

To specify the order of your results, pass an interface specifying the sort fields and directions to the SetSort() method of a read operation's options.

次の読み取り操作メソッドの最後のパラメーターとしてオプションを指定します。

  • Find()

  • FindOne()

  • FindOneAndDelete()

  • FindOneAndUpdate()

  • FindOneAndReplace()

  • gridfs.Bucket.Find()

The sort direction can be ascending or descending.

昇順で並べ替えると、結果が最小から最大の順に並べられます。この並べ替えを指定するには、並べ替えるフィールドと 1SetSort() メソッドに渡します。

Tip

昇順ソートでは、このメソッドは、Boolean 型の値を false から true に、String 型の値を a から z に、数値型の値を 負の無限大から正の無限大に 並べ替えます。

次の例では、rating フィールドで昇順の並べ替えを指定します。

filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"rating", 1}})
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)
}

降順で並べ替えると、結果が最大から最小の順に並べられます。この並べ替えを指定するには、並べ替えるフィールドと -1SetSort() メソッドに渡します。

Tip

降順ソートでは、メソッドは、Boolean 型の値を true から false に、String 型の値を z から a に、数値型の値を 正の無限大から負の無限大 に並べ替えます。

次の例では、rating フィールドで降順の並べ替えを指定します。

filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"rating", -1}})
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)
}

結果を並べ替えるために使用しているフィールドで 2 つ以上のドキュメントが同じ値を持つ場合、同順位となります。MongoDB は、同点が発生した場合の順序を保証しません。

For example, in the sample data, there is a tie for the rating in the following documents:

[{_id ObjectID("...")} {type Assam} {rating 5}]
[{_id ObjectID("...")} {type English Breakfast} {rating 5}]

To guarantee a specific order for documents when ties occur, specify additional fields to sort by.

The following example specifies an ascending sort on the rating field, then a descending sort on the type field:

filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"rating", 1}, {"type", -1}})
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 $sort stage to specify a sort in an aggregation pipeline.

次の例では、rating フィールドで降順の並べ替えを指定し、次に type フィールドで昇順の並べ替えを指定します。

sortStage := bson.D{{"$sort", bson.D{{"rating", -1}, {"type", 1}}}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage})
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 ドキュメントを参照してください。

フィードバックを送る