Overview
MongoDB Search を使用すると、 MongoDB Searchインデックスで定義したフィールドに対して、結果を昇順または降順でソートできます。sort オプションを使用して、次のフィールドタイプで並べ替えることができます。
booleandatenumber(整数、浮動小数、double 値)objectIduuidstring(トークンの種類としてインデックス付け)
結果内のドキュメントのスコアや、null 値で並べ替えたりできます。
sort オプションの互換性
Atlas は、 MongoDB 7.0 以降のバージョンのすべてのメジャー リリースとマイナー リリースに対して、シャーディングされていないソートクエリとシャーディングされたソートクエリの両方をサポートしています。
sort オプションの制限
embeddedDocuments型のフィールドではソートできません。
非推奨の knnBeta 演算子では
sortオプションは使用できません。
使用法
MongoDB Search の結果を並べ替えるには、次の操作を行う必要があります。
結果を並べ替えるには、 フィールドにMongoDB Searchインデックスを作成します。
boolean、date、number、UUID、objectIdフィールドで並べ替えるには、動的マッピングまたは静的マッピングを使用します。 string フィールドでソートするには、静的マッピングを使用してフィールドをtokenタイプとしてインデックス付けする必要があります。Create and run your query with the
sortoption against the fields you defined in the index for sorting. To learn more, see Syntax.
動作
ブール値、日付、数値、UUID、ObjectId、または string フィールドでソート
The sort option takes a document that specifies the fields to sort by and the respective sort order. MongoDB Search follows the MongoDB comparison order for the supported data types. It treats UUID values like BinData. To learn more, see non-existent fields.
次の並べ替え順序を指定して、結果を並べ替えることができます。
| 昇順でソートします。 昇順でソートすると、 MongoDB Search は、 値を持つドキュメントの前に欠損値を持つドキュメントを返します。 |
| 降順でソートします。 |
スコアと一意のフィールドで並べ替え
You can also sort by score in ascending or descending order. The sort option takes a document that specifies the $meta expression, which requires the searchScore value.
例
アプリケーションで、ユーザーが検索結果の最後のページにスキップできるとします。 次の例では、結果をスコアの昇順でソートし、スコアが最も低いドキュメントが結果の上部に表示されるようにします。
sort: {score: {$meta: "searchScore", order: 1}}
sort を使用すると、結果内の複数のドキュメントのスコアが同じである場合に、結果の順序が特定の順序になるようにすることもできます。例、次の例に示すように、lastUpdated という名前の日付フィールドなど、 一意のフィールドで結果をソートすると、 MongoDB Search は決定された順序で同じスコアを持つ結果を返します。
例
sort: {score: {$meta: "searchScore"}, lastUpdated: 1}
ただし、結果を並べ替えるための一意のフィールドを指定しない場合、 MongoDB Search はスコアの降順で並べ替えられた結果を返します。MongoDB Search では、スコアまたは値が同一の結果が任意の順序で返されます。次の例では、結果を一意のフィールドでソートしません。
例
sort: {score: {$meta: "searchScore"}}
配列のソート
MongoDB Search は、ソート用に配列をフラット化します。
例
次の配列について考えてみましょう。
[4, [1, [8,5], 9], 2]
MongoDB Search は、次のように、前述の配列をフラット化します。
4, 1, 8, 5, 9, 2
昇順 並べ替えでは、 MongoDB Search は 1 を使用して配列を他の値と比較します。降順並べ替えでは、 MongoDB Search は 9 を使用して配列を他の値と比較します。
配列内の要素と比較する場合:
昇順ソートでは、 MongoDB Search は配列の最小要素を比較するか、(
<)未満の比較を実行します。例
MongoDB Search では、数値で昇順にソートすると、次の順序で結果がソートされます。
-20 [-3, 12] // <- -3 comes before 5. 5 [6, 18] // <- 6 comes after 5. 13 14 降順ソートでは、 MongoDB Search は配列の最大要素を比較するか、(
>)より大きい比較を実行します。例
MongoDB Search では、数値で降順にソートすると、次の順序で結果がソートされます。
[6, 18] // <- 18 comes before 14. 14 13 [-3, 12] // <- 12 comes after 13. 5 -20
複数のタイプで配列をソートする
When sorting over array fields that contain values of multiple BSON types, MongoDB Search selects a representative element from the array to use for comparison according to the MongoDB comparison and sort order by default.
昇順ソートの場合、 MongoDB Search はBSON型の最も低い要素を使用します。
降順ソートの場合、 MongoDB Search は最も高いBSON type の要素を使用します。
配列内に同じ BSON 型の値が複数ある場合、選択した型の標準ソート動作が適用されます。
例
次の配列について考えてみましょう。
[ 'foo', null, 15, true, false ]
For an ascending sort, MongoDB Search uses
null, as it is the lowest supported BSON type.降順でソートする場合、MongoDB Search は
trueを使用します。これは配列内で最も高い BSON 型であるため、MongoDB Search はtrue値をfalse値よりも上位にランク付けします。
ただし、 sort 構文で noData: highest を設定すると、 MongoDB Search は null 値と欠損値を最上位のBSON型と見なします。例配列では、次の動作が適用されます。
昇順 ソートの場合、 MongoDB Search は配列内で最低のBSON型であるため、
15を使用します。降順ソートでは、 MongoDB Search は
nullを使用します。これは配列の最上位のBSONタイプになっています。
「Null および欠損値によるソート」を参照してください。
For an example, see Sort on Multi-Typed Arrays.
Null および欠損値でソート
MongoDB Search では、null 値は欠落値と空の値と等しいものとして扱われ、これらの値を持つドキュメントの順序はソート時に非決定的になります。
By default, MongoDB Search follows the MongoDB comparison and sort order and considers null values as lower than all other supported BSON types. Therefore, null values appear at the top of the results during an ascending sort and at the bottom during a descending sort.
To configure where null values appear in the results, specify the noData field in your sort syntax. The noData field takes the following values:
lowest(デフォルト): ソート中に null 値を最小のBSONタイプとして設定します。昇順ソートでは null 値を結果の上部に、降順ソートでは最下位でソートします。highest: ソート時に null 値を最上位のBSONタイプとして設定します。昇順ソートでは null 値を結果の下にソートし、降順ソートでは null 値を上部にソートします。
注意
The same behavior applies when sorting on arrays with multiple types that contain null or missing values.
例については、「 null 値によるソート 」および「 マルチタイプ配列でのソート 」を参照してください。
埋め込みドキュメント配列フィールドでのソート
埋め込まれたドキュメント フィールドで親ドキュメントをソートするには、次の操作を行う必要があります。
埋め込まれたドキュメント子フィールドの親をドキュメントタイプとしてインデックス化します。
MongoDB Search は親ドキュメントのみをソートします。ドキュメントの配列内の子フィールドはソートされません。の例については、「 ソートの例 」を参照してください。
Considerations
整合性
MongoDB Search インデックスは結果整合性があり、結果で返される値はソートで使用される値と異なる場合があります。
パフォーマンス
This feature optimizes queries that use $search with $limit as a subsequent stage. If MongoDB Search needs to sort all documents in the collection, the response might be slow.
スコアリング
MongoDB Search では、結果内にすべてのドキュメントのスコアが返されます。ただし、スコアで明示的に並べ替えない限り、結果内のドキュメントの順序が並べ替え条件に基づいているため、スコアの低いドキュメントの後にスコアの高いドキュメントが表示される可能性があります。
構文
sort の構文は次のとおりです。
1 { 2 "$search": { 3 "index": "<index name>", // optional, defaults to "default" 4 "<operator>": { // such as "text", "compound", or "phrase" 5 <operator-specification> 6 }, 7 "sort": { 8 score: {$meta: "searchScore"}, // optional field 9 "<field-to-sort>": <sort-order>, // 1 or -1, or a document 10 ... 11 } 12 } 13 }
Parameter | 説明 | |||||
|---|---|---|---|---|---|---|
| Optional. Determines whether to sort by the search score. To learn more, see Sort by Score And a Unique Field. | |||||
| 必須。 並べ替えるフィールドの名前。 | |||||
| 必須。 ソート順序を決定します。 昇順には If you want to specify the noData field, use a document with the following syntax: |
例
次の例では、 sample_mflix.movies 、 sample_airbnb.listingsAndReview 、またはusersという名前のカスタム コレクションを使用します。
インデックスの定義
このページのサンプル クエリでは、 sample_mflix.movies 、 sample_airbnb.listingsAndReview 、またはカスタム コレクションのいずれかを使用します。 これらのコレクションに次のインデックスを作成すると、インデックス フィールドに対してサンプル クエリを実行できます。
日付検索とソート
次のクエリは、複合演算子クエリを実行し、結果を日付フィールドでソートする方法を示しています。次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summerで始まる映画タイトルを検索できます。
クエリは、次のパイプライン ステージを使用します。
数値検索とソート
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
string 検索とソート
基本的な例
sample_mflix.movies名前空間に対する次のクエリでは、 $searchステージを使用して次の処理が行われます。
タイトルに
countryというタームが含まれる映画を検索します。sortオプションを使用して、結果を昇順で並べ替えます。
The query uses the $limit stage to limit the output to 5 documents. It also uses the $project stage to do the following:
結果の
titleを除くすべてのフィールドを省略します。scoreという名前のフィールドを追加します。
db.movies.aggregate([ { "$search": { "text": { "path": "title", "query": "country" }, "sort": { "title": 1 } } }, { "$limit": 5 }, { "$project": { "_id": 0, "title": 1, "score": { "$meta": "searchScore" } } } ])
複合ワイルドカード検索とソートの例
次のクエリは、結果を string フィールドでクエリしてソートする方法を示しています。 PranceまたはPrinceで始まるタイトルを検索し、結果をtitleフィールドで昇順にソートします。
クエリは、次のパイプライン ステージを使用します。
大文字と小文字を区別しないソートの例
次のクエリは、大文字と小文字に関係なく結果をソートする方法を示しています。 テキスト演算子を使用して、 titleフィールドにtrainというタームが含まれる映画を検索し、その結果をtitleフィールド値で昇順にソートします。
The query specifies a $limit stage to limit the documents in the results to 5 and a $project stage to do the following:
結果には
_id、title、awardsフィールドのみが結果に含まれます。結果にスコアという名前のフィールドを追加する。
ObjectId でソート
次のクエリは、範囲演算子を使用して、 sample_mflix.moviesコレクションのreleasedフィールドで、 2015-01-01と2015-12-31の間に公開された映画を検索します。 結果は、タイプObjectIdの値を含む_idフィールドで降順にソートされます。
db.movies.aggregate([ { "$search": { "range": { "path": "released", "gt": ISODate("2015-01-01T00:00:00.000Z"), "lt": ISODate("2015-12-31T00:00:00.000Z") }, "sort": { "_id": -1 } } }, { "$limit": 5 }, { "$project": { "_id": 1, "title": 1, "released": 1, "score": { "$meta": "searchScore" } } } ])
UUID でソート
次のクエリは、 usersコレクションのフィールドbでhelloというタームを検索します。 クエリでは、多形データ(ソート順序を示すため)を含むフィールドaで結果が昇順でソートされます。
db.users.aggregate([ { "$search": { "text": { "path": "b", "query": "hello" }, "sort": { "a": 1 } } }, { "$project": { "_id": 1, "a": 1, "score": { "$meta": "searchScore" } } } ])
NULL 値でソート
テキスト 演算子を使用して、フィールド で bコレクション内の文字列hellousers を検索する次のクエリを検討してみましょう。次に、クエリは結果をフィールドc でソートします。このフィールドにはコレクション内の一部のドキュメントに null または欠損値が含まれています。
「Null および欠損値によるソート」を参照してください。
注意
noData: lowest の設定はデフォルトの と同じです。
MongoDB Search はソート時に null 値と欠損値を等しいものとして扱うため、"_id": 4、"_id": 5、"_id": 6 を含むドキュメントの順序はランダムです。
複数の型の配列でのソート
Consider the following queries on the users collection given an additional document with a multi-typed array in field c:
db.users.insertOne({ "_id": 7, "a": UUID("03e32aa9-1cbd-43b8-b9d6-18b171a03cc7"), "b": "hello", "c": [ false, null, 15 ] })
bhello次のクエリは、テキスト演算子を使用してフィールド で文字列 を検索し、その結果をフィールドc でソートします。
注意
noData: lowest並べ替え構文で を設定する方法は、デフォルトのと同じです。
次のクエリは、ソート時に null 値を最も高い BSON 型として設定するために noData: highest を指定します。
ブール値でソート
次のクエリは、 sample_airbnb.listingsAndReviewsコレクションでPortugalの プロパティを検索し、その結果をbooleanフィールドis_location_exactの降順で並べ替えます。
The query uses the $limit stage to limit the output to 5 documents. It also uses the $project stage to omit all fields except name, property_type, address.country, and address.location.is_location_exact in the results.
1 db.listingsAndReviews.aggregate([ 2 { 3 "$search": { 4 "text": { 5 "path": "address.country", 6 "query": "Portugal" 7 }, 8 "sort": { 9 "address.location.is_location_exact": -1, 10 } 11 } 12 }, 13 { 14 "$limit": 5 15 }, 16 { 17 "$project": { 18 "_id": 0, 19 "name": 1, 20 "property_type": 1, 21 "address.country": 1, 22 "address.location.is_location_exact": 1 23 } 24 } 25 ])
前述の結果では、ドキュメントの is_location_exact の値は true です。降順ソートでは、 MongoDB Search は true の値を false の値より超えてランク付けするためです。前のクエリの 9 行の値を 1 に変更して昇順ソートを実行すると、 MongoDB Search は false の値が true 値よりも高いドキュメントをランク付けし、次のドキュメントを返します。
[ { name: 'Ribeira Charming Duplex', property_type: 'House', address: { country: 'Portugal', location: { is_location_exact: false } } }, { name: 'Be Happy in Porto', property_type: 'Loft', address: { country: 'Portugal', location: { is_location_exact: false } } }, { name: 'Downtown Oporto Inn (room cleaning)', property_type: 'Hostel', address: { country: 'Portugal', location: { is_location_exact: false } } }, { name: 'A Casa Alegre é um apartamento T1.', property_type: 'Apartment', address: { country: 'Portugal', location: { is_location_exact: false } } }, { name: 'FloresRooms 3T', property_type: 'Apartment', address: { country: 'Portugal', location: { is_location_exact: false } } } ]
複合検索とソート
次のクエリでは、 $searchステージを使用して次の操作を実行します。
タイトルに
danceというタームが含まれる映画を検索します。2 つ以上の賞を受賞し、1990 年 1 月 1 日以降にリリースされた映画が優先されます。結果を賞の数で降順に並べ替え、次に映画タイトルの昇順で並べ替え、次に公開日の降順で並べ替えます。
The query uses the $limit stage to limit the output to 10 documents. It also uses the $project stage to do the following:
結果の
title、released、awards.wins以外のすべてのフィールドを省略します。scoreという名前のフィールドを追加します。
db.movies.aggregate([ { "$search": { "compound": { "must": [{ "text": { "path": "title", "query": "dance" } }], "should": [{ "range": { "path": "awards.wins", "gte": 2 } }, { "range": { "path": "released", "gte": ISODate("1990-01-01T00:00:00.000Z") } }] }, "sort": { "awards.wins": -1, "title": 1, "released": -1 } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "released": 1, "awards.wins": 1, "score": { "$meta": "searchScore" } } } ])
ファセット検索とソート
次のクエリでは、 $searchステージを使用して次の操作を実行します。
範囲演算子を使用して、2010 年 1 月 1 日から 2015 年 1 月 01 日の間に公開された映画を検索します。
1、5、10、15の各賞を受賞した映画の数を取得します。2010-01-01、2011-01-01、2012-01-01、2013-01-01、2014-01-01、2015-01-01でリリースされた映画の数を取得します。sortオプションを使用して、結果をリリース日の降順で並べ替えます。
The query uses the $limit stage to do the following:
docs出力フィールドの5ドキュメントに出力を制限します。meta出力フィールドの1ドキュメントへの出力を制限します。
It uses the $project stage to omit all fields except the awards.wins, released, and title fields.
It also uses the $replaceWith stage to include the metadata results stored in the $$SEARCH_META variable in the meta output field and the $set stage to add the meta field to the results.
db.movies.aggregate([ { "$search": { "facet": { "operator": { "range": { "path": "released", "gt": ISODate("2010-01-01T00:00:00.000Z"), "lt": ISODate("2015-01-01T00:00:00.000Z") } }, "facets": { "awardsFacet": { "type": "number", "path": "awards.wins", "boundaries" : [1,5,10,15] }, "releasedFacet" : { "type" : "date", "path" : "released", "boundaries" : [ISODate("2010-01-01T00:00:00.000Z"), ISODate("2011-01-01T00:00:00.000Z"), ISODate("2012-01-01T00:00:00.000Z"), ISODate("2013-01-01T00:00:00.000Z"), ISODate("2014-01-01T00:00:00.000Z"), ISODate("2015-01-01T00:00:00.000Z")] } } }, "sort": { "released": -1 } } }, { "$facet": { "docs": [ { "$limit": 5 }, { "$project": { "_id": 0, "title": 1, "released": 1, "awards.wins": 1 } } ], "meta": [ {"$replaceWith": "$$SEARCH_META"}, {"$limit": 1} ] } }, { "$set": { "meta": { "$arrayElemAt": ["$meta", 0] } } } ])
スコアで並べ替え
次の例は、結果内のドキュメントのスコアで結果を並べ替える方法を示しています。 例では、次のアクションを実行する方法が示されています。
最初に、結果を昇順でソートして、スコアが最も低いドキュメントを取得します。
結果をスコアの降順で並べ替え、スコアが同じ結果の場合は任意に並べ替えます。
結果をスコアで並べ替え、スコアが同一の結果については、 一意の フィールドを使用して並べ替えます。