AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

MongoDB Search 結果のソート

MongoDB Search を使用すると、 MongoDB Searchインデックスで定義したフィールドに対して、結果を昇順または降順でソートできます。sort オプションを使用して、次のフィールドタイプで並べ替えることができます。

  • boolean

  • date

  • number (整数、浮動小数、double 値)

  • objectId

  • uuid

  • stringトークンの種類としてインデックス付け)

結果内のドキュメントのスコアや、null 値で並べ替えたりできます。

Atlas は、 MongoDB 7.0 以降のバージョンのすべてのメジャー リリースとマイナー リリースに対して、シャーディングされていないソートクエリとシャーディングされたソートクエリの両方をサポートしています。

  • embeddedDocuments型のフィールドではソートできません。

  • 非推奨の knnBeta 演算子では sort オプションは使用できません。

MongoDB Search の結果を並べ替えるには、次の操作を行う必要があります。

  1. 結果を並べ替えるには、 フィールドにMongoDB Searchインデックスを作成します。

    booleandatenumberUUIDobjectIdフィールドで並べ替えるには、動的マッピングまたは静的マッピングを使用します。 string フィールドでソートするには、静的マッピングを使用してフィールドをtokenタイプとしてインデックス付けする必要があります。

  2. 並べ替え用インデックスで定義したフィールドに対してsortオプションを使用してクエリを作成し、実行します。 詳しくは、「構文 」を参照してください。

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.

次の並べ替え順序を指定して、結果を並べ替えることができます。

1

昇順でソートします。

昇順でソートすると、 MongoDB Search は、 値を持つドキュメントの前に欠損値を持つドキュメントを返します。

-1

降順でソートします。

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

複数のBSON types の値を含む配列フィールドをソートする場合、 MongoDB Search は 配列から表される要素を選択し、MongoDBの 比較とソートデフォルトに従って比較に使用します。

  • 昇順ソートの場合、 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.

  • For a descending sort, MongoDB Search uses true, as it is the highest BSON type in the array and MongoDB Search ranks true values above false values.

ただし、 sort 構文noData: highest を設定すると、 MongoDB Search は null 値と欠損値を最上位のBSON型と見なします。例配列では、次の動作が適用されます。

  • 昇順 ソートの場合、 MongoDB Search は配列内で最低のBSON型であるため、15 を使用します。

  • 降順ソートでは、 MongoDB Search は null を使用します。これは配列の最上位のBSONタイプになっています。

Null および欠損値によるソート」を参照してください。

例については、「マルチタイプの配列でのソート」を参照してください。

MongoDB Search では、null 値は欠落値と空の値と等しいものとして扱われ、これらの値を持つドキュメントの順序はソート時に非決定的になります。

デフォルトでは、MongoDB Search はMongoDB の比較とソート順序に従い、null 値はサポートされている他のすべてのBSON型よりも低い値と見なします。そのため、昇順ソートでは null 値が結果の上部に表示され、降順ソートでは結果の最下位に表示されます。

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 値によるソート 」および「 マルチタイプ配列でのソート 」を参照してください。

埋め込まれたドキュメント フィールドで親ドキュメントをソートするには、次の操作を行う必要があります。

  • 埋め込まれたドキュメント子フィールドの親をドキュメントタイプとしてインデックス化します。

  • 埋め込みドキュメント内のstring値を持つ子フィールドをトークンタイプとしてインデックスします。 数値値と日付値を持つ子フィールドの場合は、動的マッピングを有効にして、それらのフィールドを自動的にインデックス化します。

MongoDB Search は親ドキュメントのみをソートします。ドキュメントの配列内の子フィールドはソートされません。の例については、「 ソートの例 」を参照してください。

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
説明

score

Optional. Determines whether to sort by the search score. To learn more, see Sort by Score And a Unique Field.

<field-to-sort>

必須。 並べ替えるフィールドの名前。

<sort-order>

必須。 ソート順序を決定します。 昇順には 1 を使用し、降順には -1 を使用します。

If you want to specify the noData field, use a document with the following syntax:

"<field-to-sort>": {
order: 1 | -1, // required field
noData: "lowest" | "highest" // optional field
},
...

次の例では、 sample_mflix.moviessample_airbnb.listingsAndReview 、またはusersという名前のカスタム コレクションを使用します。

このページのサンプル クエリでは、 sample_mflix.moviessample_airbnb.listingsAndReview 、またはカスタム コレクションのいずれかを使用します。 これらのコレクションに次のインデックスを作成すると、インデックス フィールドに対してサンプル クエリを実行できます。

moviesコレクションのインデックス定義では、次の内容を指定します。

  • インデックスawards.winsフィールドは次のようになります。

  • インデックスreleasedフィールドは次のようになります。

  • インデックスtitleフィールドは次のようになります。

    • token ソート用のタイプ

    • string クエリのタイプ

1{
2 "mappings": {
3 "dynamic": true,
4 "fields": {
5 "awards": {
6 "dynamic": false,
7 "fields": {
8 "wins": [
9 {
10 "type": "number"
11 }
12 ]
13 },
14 "type": "document"
15 },
16 "released": [
17 {
18 "type": "date"
19 }
20 ],
21 "title": [{
22 "type": "token"
23 }, {
24 "type": "string"
25 }]
26 }
27 }
28}

上記のインデックス定義では、 MongoDB Search は、指定されたフィールドの静的マッピングを含む default という名前のインデックスを作成します。

この例では、 sample_airbnb.listingsAndReviewsコレクションに対するクエリで次のインデックスを使用します。 インデックス定義は、コレクション内のフィールドの 動的マッピング を指定します。

{
"mappings": {
"dynamic": true
}
}

users コレクションには次のドキュメントが含まれます。

db.users.insertMany([
{
"_id": 0,
"a": UUID("1a324de2-e34b-c87e-f2a1-42ce37ad74ed"),
"b": "hello",
"c": ObjectId("507f1f77bcf86cd799439011")
},
{
"_id": 1,
"a": UUID("3b241101-e2bb-4255-8caf-4136c566a962"),
"b": "hello",
"c": true
},
{
"_id": 2,
"a": UUID("dee11d4e-63c6-4d90-983c-5c9f1e79e96c"),
"b": "hello",
"c": "foo"
},
{
"_id": 3,
"b": "hello",
"c": UUID("3be11d4e-62cb-4e95-9a3c-5c9f1e56c732")
},
{
"_id": 4,
"a": UUID("d3c12e1c-c36e-25ed-7c3e-1e7f1e53c752"),
"b": "hello",
"c": null
},
{
"_id": 5,
"a": UUID("d73f181e-cdda-42b4-b844-4d6e172e9bc8"),
"b": "hello",
"c": []
}
{
"_id": 6,
"a": UUID("7eeddf21-b313-4a5c-81c2-c68915daa618"),
"b": "hello",
}
])

usersコレクションのインデックス定義では、次の内容を指定します。

  • cという名前のフィールドを除くすべてのフィールドを動的にインデックス化します。

  • cという名前のフィールドを、並べ替え用の次のタイプとして静的にインデックス化します。

    • token

    • uuid

    • objectId

    • boolean

1{
2 "mappings": {
3 "dynamic": true,
4 "fields": {
5 "c": [
6 { "type": "token" },
7 { "type": "uuid" },
8 { "type": "objectId" },
9 { "type": "boolean" },
10 { "type": "number" }
11 ]
12 }
13 }
14}

MongoDB Search は、前述のコレクションに対して、指定されたフィールドの指定されたマッピングで default という名前のインデックスを作成します。

次のクエリは、複合演算子クエリを実行し、結果を日付フィールドでソートする方法を示しています。次の演算子を使用します。

  • ワイルドカード演算子を使用すると、 Summerで始まる映画タイトルを検索できます。

  • near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。

    注意

    日付フィールドで pivot を使用する場合、その測定単位はミリ秒単位になります。MongoDB Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。詳しくは、の近くを参照してください。

クエリは、次のパイプライン ステージを使用します。

  • ステージでは、$search フィールドとtitle releasedフィールドを検索し、その結果を フィールドで降順にソートします。released

  • $limit stage to limit the output to 5 results.

  • $project stageを次のように設定します。

    • titlereleasedを除くすべてのフィールドを除外します。

    • scoreという名前のフィールドを追加します。

次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。

クエリは、次のパイプライン ステージを使用します。

  • $searchステージでは、 awards.winsフィールドを検索し、結果を降順でソートします。

  • $limit stage to limit the output to 5 results.

  • $project stage to exclude all fields except title and awards.wins.

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" }
}
}
])
[
{ title: 'A Country Called Home', score: 2.536633253097534 },
{ title: 'A Month in the Country', score: 2.258953094482422 },
{ title: 'A Quiet Place in the Country', score: 2.0360684394836426 },
{ title: 'A Sunday in the Country', score: 2.258953094482422 },
{ title: 'Another Country', score: 3.3635599613189697 }
]

次のクエリは、結果を string フィールドでクエリしてソートする方法を示しています。 PranceまたはPrinceで始まるタイトルを検索し、結果をtitleフィールドで昇順にソートします。

クエリは、次のパイプライン ステージを使用します。

  • $searchは、ワイルドカード演算子とともにshould句を使用してtitleフィールドを検索し、 PrancePrinceで始まるタイトルを検索します。 このクエリでは、結果がtitleフィールドで昇順にソートされる必要があることも指定しています。

  • $limit stage to limit the output to 5 results.

  • $project stageを次のように設定します。

    • titleを除くすべてのフィールドを除外します。

    • scoreという名前のフィールドを追加します。

次のクエリは、大文字と小文字に関係なく結果をソートする方法を示しています。 テキスト演算子を使用して、 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:

  • 結果には_idtitleawardsフィールドのみが結果に含まれます。

  • 結果にスコアという名前のフィールドを追加する。

次のクエリは、範囲演算子を使用して、 sample_mflix.moviesコレクションのreleasedフィールドで、 2015-01-012015-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" }
}
}
])
[
{
_id: ObjectId('573a13fbf29313caabdedf31'),
title: 'No Home Movie',
released: ISODate('2015-08-10T00:00:00.000Z'),
score: 1
},
{
_id: ObjectId('573a13fbf29313caabdedf30'),
title: 'Our Loved Ones',
released: ISODate('2015-08-12T00:00:00.000Z'),
score: 1
},
{
_id: ObjectId('573a13faf29313caabded406'),
title: 'The Red Spider',
released: ISODate('2015-11-20T00:00:00.000Z'),
score: 1
},
{
_id: ObjectId('573a13faf29313caabded1d6'),
title: 'The Laundryman',
released: ISODate('2015-07-11T00:00:00.000Z'),
score: 1
},
{
_id: ObjectId('573a13faf29313caabdecaf3'),
title: 'Right Now, Wrong Then',
released: ISODate('2015-09-01T00:00:00.000Z'),
score: 1
}
]

次のクエリは、 usersコレクションのフィールドbhelloというタームを検索します。 クエリでは、多形データ(ソート順序を示すため)を含むフィールドaで結果が昇順でソートされます。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"a": 1
}
}
},
{
"$project": {
"_id": 1,
"a": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 3, score: 0.029335692524909973 },
{
_id: 0,
a: UUID('1a324de2-e34b-c87e-f2a1-42ce37ad74ed'),
score: 0.029335692524909973
},
{
_id: 1,
a: UUID('3b241101-e2bb-4255-8caf-4136c566a962'),
score: 0.029335692524909973
},
{
_id: 6,
a: UUID('7eeddf21-b313-4a5c-81c2-c68915daa618'),
score: 0.029335692524909973
},
{
_id: 4,
a: UUID('d3c12e1c-c36e-25ed-7c3e-1e7f1e53c752'),
score: 0.029335692524909973
},
{
_id: 5,
a: UUID('d73f181e-cdda-42b4-b844-4d6e172e9bc8'),
score: 0.029335692524909973
},
{
_id: 2,
a: UUID('dee11d4e-63c6-4d90-983c-5c9f1e79e96c'),
score: 0.029335692524909973
}
]

テキスト 演算子を使用して、フィールド で bコレクション内の文字列hellousers を検索する次のクエリを検討してみましょう。次に、クエリは結果をフィールドc でソートします。このフィールドにはコレクション内の一部のドキュメントに null または欠損値が含まれています。

Null および欠損値によるソート」を参照してください。

昇順ソート中に、 MongoDB Search は、次の例に示すように、デフォルトで 、null または欠落値が結果の上部に null または欠落値を持つドキュメントを返します。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": { "c": 1 }
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 4, c: null, score: 0.029335692524909973 },
{ _id: 5, c: [], score: 0.029335692524909973 },
{ _id: 6, score: 0.029335692524909973 },
{ _id: 2, c: 'foo', score: 0.029335692524909973 },
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.029335692524909973
},
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.029335692524909973
},
{ _id: 1, c: true, score: 0.029335692524909973 }
]

降順ソート中に、 MongoDB Search は、次の例に示すように、デフォルトで 、null または欠落値が結果の下部にあるドキュメントを返します。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": { "c": -1 }
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 1, c: true, score: 0.025981096550822258 },
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{ _id: 2, c: 'foo', score: 0.025981096550822258 },
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 }
]

注意

noData: lowest の設定はデフォルトの と同じです。

昇順ソート中に noDataフィールドを lowest として指定すると、 MongoDB Search は、次の例に示すように、null または欠損値が結果の上部にあるドキュメントを返します。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": {
"order": 1,
"noData": "lowest"
}
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 4, c: null, score: 0.029335692524909973 },
{ _id: 5, c: [], score: 0.029335692524909973 },
{ _id: 6, score: 0.029335692524909973 },
{ _id: 2, c: 'foo', score: 0.029335692524909973 },
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.029335692524909973
},
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.029335692524909973
},
{ _id: 1, c: true, score: 0.029335692524909973 }
]

降順ソート中に noDataフィールドを lowest として指定すると、 MongoDB Search は、次の の例に示すように、結果の下部に null または欠落値を含むドキュメントを返します。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": {
"order": -1,
"noData": "lowest"
}
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 1, c: true, score: 0.025981096550822258 },
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{ _id: 2, c: 'foo', score: 0.025981096550822258 },
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 }
]

昇順ソート中に noDataフィールドを highest として指定すると、 MongoDB Search は、次の例に示すように、null または欠損値が結果の下部にあるドキュメントを返します。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": {
"order": 1,
"noData": "highest"
}
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 2, c: 'foo', score: 0.025981096550822258 },
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{ _id: 1, c: true, score: 0.025981096550822258 },
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 }
]

降順ソート中に noDataフィールドを highest として指定すると、 MongoDB Search は、次の例に示すように、null または欠損値が結果の上部にあるドキュメントを返します。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": {
"order": -1,
"noData": "highest"
}
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 },
{ _id: 1, c: true, score: 0.025981096550822258 },
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{ _id: 2, c: 'foo', score: 0.025981096550822258 }
]

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並べ替え構文で を設定する方法は、デフォルトのと同じです。

For an ascending sort, MongoDB Search uses the element with the lowest BSON type to represent the multi-typed array. By default, MongoDB Search considers null or missing values as the lowest BSON value. Therefore, MongoDB Search uses null to represent the multi-typed array for the document with _id: 7 and returns this document at the top of the results along with other null and missing values.

詳細については、「 Null および欠損値によるソート 」および「 複数のタイプを使用した配列のソート 」を参照してください。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": 1
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 }
{ _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
{ _id: 2, c: 'foo', score: 0.025981096550822258 },
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{ _id: 1, c: true, score: 0.025981096550822258 }
]

MongoDB Search はソート時に null 値と欠損値を等しいものとして扱うため、"_id": 4"_id": 5"_id": 6"_id": 7 を含むドキュメントの順序はランダムです。

For a descending sort, MongoDB Search uses the element with the highest BSON type to represent the multi-typed array. MongoDB Search uses false to represent the multi-typed array for the document with _id: 7, as this is the highest BSON type in the array. Since MongoDB Search also ranks true values above false values, MongoDB Search returns this document after the document with _id: 1.

詳細については、「 Null および欠損値によるソート 」および「 複数のタイプを使用した配列のソート 」を参照してください。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": -1
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 1, c: true, score: 0.025981096550822258 },
{ _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{ _id: 2, c: 'foo', score: 0.025981096550822258 }
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 },
]

MongoDB Search はソート時に null 値と欠損値を等しいものとして扱うため、"_id": 4"_id": 5"_id": 6 を含むドキュメントの順序はランダムです。

次のクエリは、ソート時に null 値を最も高い BSON 型として設定するために noData: highest を指定します。

For an ascending sort, MongoDB Search uses the element with the lowest BSON type to represent the multi-typed array. The query specifies noData: highest to consider null or missing values as the highest BSON value, so MongoDB Search uses 15 to represent the multi-typed array for the document with _id: 7 since numbers are the next lowest BSON type in the array.

詳細については、「 Null および欠損値によるソート 」および「 複数のタイプを使用した配列のソート 」を参照してください。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": {
"order": 1,
"noData": "highest"
}
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
{ _id: 2, c: 'foo', score: 0.025981096550822258 },
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{ _id: 1, c: true, score: 0.025981096550822258 },
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 }
]

MongoDB Search はソート時に null 値と欠損値を等しいものとして扱うため、"_id": 4"_id": 5"_id": 6 を含むドキュメントの順序はランダムです。

For a descending sort, MongoDB Search uses the element with the highest BSON type to represent the multi-typed array. Since the query specifies the noData field as highest to set null or missing values as the highest BSON value, MongoDB Search uses null to represent the multi-typed array for the document with _id: 7 and returns this document at the top of the results along with other null and missing values.

詳細については、「 Null および欠損値によるソート 」および「 複数のタイプを使用した配列のソート 」を参照してください。

db.users.aggregate([
{
"$search": {
"text": {
"path": "b",
"query": "hello"
},
"sort": {
"c": {
"order": -1,
"noData": "highest"
}
}
}
},
{
"$project": {
"_id": 1,
"c": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{ _id: 4, c: null, score: 0.025981096550822258 },
{ _id: 5, c: [], score: 0.025981096550822258 },
{ _id: 6, score: 0.025981096550822258 },
{ _id: 7, c: [ false, null, 15 ], score: 0.025981096550822258 },
{ _id: 1, c: true, score: 0.025981096550822258 },
{
_id: 0,
c: ObjectId('507f1f77bcf86cd799439011'),
score: 0.025981096550822258
},
{
_id: 3,
c: UUID('3be11d4e-62cb-4e95-9a3c-5c9f1e56c732'),
score: 0.025981096550822258
},
{ _id: 2, c: 'foo', score: 0.025981096550822258 }
]

MongoDB Search はソート時に null 値と欠損値を等しいものとして扱うため、"_id": 4"_id": 5"_id": 6"_id": 7 を含むドキュメントの順序はランダムです。

次のクエリは、 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.

1db.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])
1[
2 {
3 name: 'BBC OPORTO 4X2',
4 property_type: 'Apartment',
5 address: { country: 'Portugal', location: { is_location_exact: true } }
6 },
7 {
8 name: 'Heroísmo IV',
9 property_type: 'Apartment',
10 address: { country: 'Portugal', location: { is_location_exact: true } }
11 },
12 {
13 name: 'Spacious and well located apartment',
14 property_type: 'Apartment',
15 address: { country: 'Portugal', location: { is_location_exact: true } }
16 },
17 {
18 name: 'Renovated Classic Design Studio with Sun Room',
19 property_type: 'Apartment',
20 address: { country: 'Portugal', location: { is_location_exact: true } }
21 },
22 {
23 name: "O'Porto Studio | Historic Center",
24 property_type: 'Loft',
25 address: { country: 'Portugal', location: { is_location_exact: true } }
26 }
27]

前述の結果では、ドキュメントの 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:

  • 結果のtitlereleasedawards.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" }
}
}
])
[
{
title: 'Shall We Dance?',
released: ISODate("1997-07-11T00:00:00.000Z"),
awards: { wins: 57 },
score: 4.9811458587646484
},
{
title: 'Shall We Dance?',
released: ISODate("1997-07-11T00:00:00.000Z"),
awards: { wins: 57 },
score: 4.9811458587646484
},
{
title: 'War Dance',
released: ISODate("2008-11-01T00:00:00.000Z"),
awards: { wins: 11 },
score: 5.466421127319336
},
{
title: 'Dance with the Devil',
released: ISODate("1997-10-31T00:00:00.000Z"),
awards: { wins: 6 },
score: 4.615056037902832
},
{
title: 'Save the Last Dance',
released: ISODate("2001-01-12T00:00:00.000Z"),
awards: { wins: 6 },
score: 4.615056037902832
},
{
title: 'Dance with a Stranger',
released: ISODate("1985-08-09T00:00:00.000Z"),
awards: { wins: 4 },
score: 3.615056037902832
},
{
title: 'The Baby Dance',
released: ISODate("1998-08-23T00:00:00.000Z"),
awards: { wins: 4 },
score: 4.981145858764648
},
{
title: 'Three-Step Dance',
released: ISODate("2004-02-19T00:00:00.000Z"),
awards: { wins: 4 },
score: 4.981145858764648
},
{
title: "Cats Don't Dance",
released: ISODate("1997-03-26T00:00:00.000Z"),
awards: { wins: 3 },
score: 4.981145858764648
},
{
title: 'Dance Me Outside',
released: ISODate("1995-03-10T00:00:00.000Z"),
awards: { wins: 3 },
score: 4.981145858764648
}
]

次のクエリでは、 $searchステージを使用して次の操作を実行します。

  • 範囲演算子を使用して、2010 年 1 月 1 日から 2015 年 1 月 01 日の間に公開された映画を検索します。

  • 151015の各賞を受賞した映画の数を取得します。

  • 2010-01-012011-01-012012-01-012013-01-012014-01-012015-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]
}
}
}
])
[
{
docs: [
{
title: 'Cold in July',
released: ISODate("2014-12-31T00:00:00.000Z"),
awards: { wins: 1 }
},
{
title: 'The Gambler',
released: ISODate("2014-12-31T00:00:00.000Z"),
awards: { wins: 7 }
},
{
title: 'Force Majeure',
released: ISODate("2014-12-30T00:00:00.000Z"),
awards: { wins: 31 }
},
{
title: 'LFO',
released: ISODate("2014-12-27T00:00:00.000Z"),
awards: { wins: 3 }
},
{
title: 'Peace After Marriage',
released: ISODate('2014-12-26T00:00:00.000Z'),
awards: { wins: 5 }
}
],
meta: {
count: { lowerBound: Long("4821") },
facet: {
releasedFacet: {
buckets: [
{
_id: ISODate("2010-01-01T00:00:00.000Z"),
count: Long("857")
},
{
_id: ISODate("2011-01-01T00:00:00.000Z"),
count: Long("909")
},
{
_id: ISODate("2012-01-01T00:00:00.000Z"),
count: Long("903")
},
{
_id: ISODate("2013-01-01T00:00:00.000Z"),
count: Long("1063")
},
{
_id: ISODate("2014-01-01T00:00:00.000Z"),
count: Long("1089")
}
]
},
awardsFacet: {
buckets: [
{ _id: 1, count: Long("2330") },
{ _id: 5, count: Long("604") },
{ _id: 10, count: Long("233") }
]
}
}
}
}
}
]

次の例は、結果内のドキュメントのスコアで結果を並べ替える方法を示しています。 例では、次のアクションを実行する方法が示されています。

  • 最初に、結果を昇順でソートして、スコアが最も低いドキュメントを取得します。

  • 結果をスコアの降順で並べ替え、スコアが同じ結果の場合は任意に並べ替えます。

  • 結果をスコアで並べ替え、スコアが同一の結果については、 一意の フィールドを使用して並べ替えます。

次のクエリは、 $searchステージを使用して次のアクションを実行します。

  • タイトルにstoryというタームが含まれる映画を検索します。

  • 結果をスコアの昇順で並べ替えます。

The query uses the $limit stage to limit the output to 5 documents. It also uses the $project stage to perform the following actions:

  • 結果のtitleを除くすべてのフィールドを省略します。

  • scoreという名前のフィールドを追加します。

db.movies.aggregate([
{
"$search": {
"text": {
"path": "title",
"query": "story"
},
"sort": {score: {$meta: "searchScore", order: 1}}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"title": 1,
"score": {$meta: "searchScore"}
}
}
])
[
{
title: 'Do You Believe in Miracles? The Story of the 1980 U.S. Hockey Team',
score: 0.8674521446228027
},
{
title: 'Once in a Lifetime: The Extraordinary Story of the New York Cosmos',
score: 0.9212141036987305
},
{
title: 'The Source: The Story of the Beats and the Beat Generation',
score: 0.9820802211761475
},
{
title: 'If These Knishes Could Talk: The Story of the NY Accent',
score: 0.9820802211761475
},
{
title: 'Dream Deceivers: The Story Behind James Vance vs. Judas Priest',
score: 1.051558256149292
}
]

次のクエリは、 $searchステージを使用して次のアクションを実行します。

  • タイトルにsummerというタームが含まれる映画を検索します。

  • 結果をスコアの降順で並べ替え、スコアが同じ結果の場合は任意に並べ替えます。

The query uses the $limit stage to limit the output to 5 documents. It also uses the $project stage to perform the following actions:

  • 結果の_idtitleを除くすべてのフィールドを省略します。

  • scoreという名前のフィールドを追加します。

db.movies.aggregate([
{
"$search": {
"text": {
"path": "title",
"query": "summer"
},
"sort": {score: {$meta: "searchScore"}}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 1,
"title": 1,
"score": {$meta: "searchScore"}
}
}
])
[
{
_id: ObjectId("573a1398f29313caabcea21e"),
title: 'Summer',
score: 3.5844719409942627
},
{
_id: ObjectId("573a13a6f29313caabd18eca"),
title: 'Summer Things',
score: 3.000213623046875
},
{
_id: ObjectId("573a13b8f29313caabd4c1d0"),
title: 'Summer Palace',
score: 3.000213623046875
},
{
_id: ObjectId("573a1394f29313caabcde8e8"),
title: 'Summer Stock',
score: 3.000213623046875
},
{
_id: ObjectId("573a13acf29313caabd284fa"),
title: 'Wolf Summer',
score: 3.000213623046875
}
]

次のクエリは、 $searchステージを使用して次のアクションを実行します。

  • タイトルにprinceというタームが含まれる映画を検索します。

  • 最初にスコアで結果を並べ替え、次にreleasedフィールドの値で昇順に並べ替え、同一のスコアを持つ結果を作成します。

The query uses the $limit stage to limit the output to 5 documents. It also uses the $project stage to perform the following actions:

  • 結果のtitlereleasedを除くすべてのフィールドを省略します。

  • scoreという名前のフィールドを追加します。

db.movies.aggregate([
{
"$search": {
"text": {
"path": "title",
"query": "prince"
},
"sort": {score: {$meta: "searchScore"}, "released": 1}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"score": {$meta: "searchScore"}
}
}
])
[
{
title: 'Prince',
released: ISODate("2015-08-14T00:00:00.000Z"),
score: 4.168826103210449
},
{
title: 'Prince Avalanche',
released: ISODate("2013-09-19T00:00:00.000Z"),
score: 3.4893198013305664
},
{
title: 'The Prince',
released: ISODate("2014-08-22T00:00:00.000Z"),
score: 3.4893198013305664
},
{
title: 'Prince of Foxes',
released: ISODate("1949-12-23T00:00:00.000Z"),
score: 3.0002830028533936
},
{
title: 'The Oil Prince',
released: ISODate("1966-01-01T00:00:00.000Z"),
score: 3.0002830028533936
}
]