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

結果のページ分割

MongoDB 7.0.5+を実行中クラスターでは、MongoDB Search を使用して、参照点の後、または 前 で $search クエリ結果を連続して取得します。$search searchAfter または searchBefore オプションを使用して結果を順番に走査し、アプリケーション内で「次のページ」と「前のページ」関数を構築します。

ページ分割された結果を検索するには、次の手順を実行します。

  1. クエリを実行したいフィールドにインデックスを作成します。

  2. 参照点を返す$searchクエリを実行します。 詳細については、「 参照点の取得 」を参照してください。

  3. 後続の$searchクエリで参照点を使用して、結果内に次または前のドキュメント セットを検索します。

  • 複数のドキュメントが同じ値を持つフィールドでソートすると、同点となります。Mongo DBは、結び付けられたクエリ結果の順序を保証しません。searchAftersearchBefore を使用すると、重複や不整合が発生する可能性があります。関連性スコアの同点を減らすために、次の原則を応用します。

    • 関連性スコアの同点を防ぐために、クエリを一意のフィールドで並べ替えます。例については、 「スコアと一意のフィールドによる並べ替え」を参照してください。

    • 非 一意のフィールドで主にソートする場合は、タイブレークとして機能するために一意のフィールドに セカンダリ ソート句を追加 します。

  • クエリ間でドキュメントを更新または削除すると、結果順序の不整合が発生する可能性があります。決定的な検索する動作をサポートするには、次の原則を適用します。

    • クエリ結果を_idなどの不変フィールドで並べ替えます。MongoDB Search は、最初のクエリと後続のクエリの間にコレクションに加えた更新を反映します。変更可能なフィールド(例:updated_time)でソートし、最初のクエリと2番目のクエリの間でコレクションを更新すると、MongoDB Search では同じドキュメントの順序が異なる場合があります。

    • 専用の検索ノードを配置し、searchScore 、結果をソートする場合は、以下を考慮してください。

      • By default, MongoDB Search scores documents using the bm25 similarity algorithm, which calculates term frequency in relation to the entire corpus of documents on the MongoDB Search node. Because each MongoDB Search node replicates from the changestream independently, this corpus might vary across MongoDB Search nodes. As a result, the same query can return different bm25 scores when routed to different MongoDB Search nodes. Subsequent queries are more likely to be routed to different MongoDB Search nodes if your deployment uses dedicated MongoDB Search nodes, or your read preference is set to secondary or nearest.

      • 以降のクエリでコンシステントなスコアが得られるようにするには、フィールドを MongoDB Search のstringまたはautocomplete型としてインデックス化するときにsimilarity.type プロパティをstableTfl あるいはboolean に設定します。これにより、textphrasequeryStringautocomplete 演算子は、インデックス付きフィールドのクエリの関連性スコアを計算するためにstableTflまたはboolean類似度アルゴリズムを使用するようになります。これらのアルゴリズムは、すべての MongoDB Search ノードで一貫してスコアを計算します。詳細については、「スコアの詳細」を参照してください。

  • To count search results during pagination, use the count option in your initial $search query or in a separate $searchMeta query. This method is more efficient than using the $count stage after your $search stage.

    count オプションは検索条件に一致するドキュメントの合計数を返すため、ページ分割された結果を生成している場合は、後のクエリで count オプションを使用する必要がありません。$searchメインの クエリとは別にカウントするには、$searchMeta オプションを指定したcount ステージを使用します。

    検索結果をカウントすると、パフォーマンスに影響する可能性があります。count オプションは必要な場合にのみ使用してください。例、最初のページの検索結果を取得する場合などです。

To retrieve query results at a certain point, you must provide the point of reference in your $search query. You can retrieve the reference point by using the $meta keyword searchSequenceToken in the $project stage after your $search stage.

searchSequenceToken 構文
1[{
2 "$search": {
3 "index": "<index-name>",
4 "<operator-name>"|"<collector-name>": {
5 <operator-specification>|<collector-specification>
6 },
7 "sort": {
8 "score": {
9 "$meta": "searchScore"
10 }
11 },
12 ...
13 },
14 {
15 "$project": {
16 "paginationToken" : { "$meta" : "searchSequenceToken" }
17 },
18 ...
19}]

searchSequenceTokenは、結果内の各ドキュメントに対して base 64でエンコードされたトークンを生成します。 トークンの長さは、クエリのソートオプションで指定されたフィールドの数に応じて増加します。 トークンはデータベースのスナップショットには関連付けられていません。

クエリで sort オプションを指定しない限り、結果内のドキュメントはデフォルトの順序でソートされます。結果の並べ替えの詳細については、「 MongoDB検索結果の並べ替え 」を参照してください。

参照点を検索するには、 searchSequenceTokenによって生成されたトークンでsearchAfterオプションを使用して、 $searchクエリで参照点を指定する必要があります。 searchSequenceTokenによって生成されたトークンは、 searchSequenceTokenがトークンを生成した$searchクエリを再実行した場合にのみ使用できます。 トークンを使用する後続の$searchクエリのセマンティクス(検索フィールドと値)は、 searchSequenceTokenがトークンを生成したクエリと同一である必要があります。

searchAfterオプションを使用して、アプリケーション内で「次のページ」機能を構築できます。 これを示すには、このページのを参照してください。

searchAfter 構文
1[{
2 "$search": {
3 "index": "<index-name>",
4 "<operator-name>"|"<collector-name>": {
5 <operator-specification>|<collector-specification>
6 },
7 "searchAfter": "<base64-encoded-token>",
8 "sort": {
9 "score": {
10 "$meta": "searchScore"
11 }
12 },
13 ...
14 },
15 "$project": {
16 "paginationToken" : { "$meta" : "searchSequenceToken" }
17 },
18 ...
19}]

MongoDB Search returns the documents in the results after the specified token. MongoDB Search returns the generated tokens for the documents in the results because you specified the searchSequenceToken in the $project stage after the $search stage (as shown in line 11). These tokens can be used as a reference point for another query with the same semantics.

クエリで sort オプションを指定しない限り、結果内のドキュメントはデフォルトの順序でソートされます。結果の並べ替えの詳細については、「 MongoDB検索結果の並べ替え 」を参照してください。

参照点の前を検索するには、 searchSequenceTokenによって生成されたトークンでsearchBeforeオプションを使用して、 $searchクエリで参照点を指定する必要があります。 searchSequenceTokenによって生成されたトークンは、 searchSequenceTokenがトークンを生成した$searchクエリを再実行した場合にのみ使用できます。 トークンを使用する後続の$searchクエリのセマンティクス(検索フィールドと値)は、 searchSequenceTokenがトークンを生成したクエリと同一である必要があります。

searchBefore オプションを使用して、アプリケーションで「前のページ」機能を構築できます。これを行うには、以下を組み合わせます。

  • $searchオプションを使用した ステージsearchBefore

  • $limit ステージ

  • toArray() and reverse() methods.

これを証明するために、このページのsearchBeforeクエリを参照してください。

searchBefore 構文
1[{
2 "$search": {
3 "index": "<index-name>",
4 "<operator-name>"|"<collector-name>": {
5 <operator-specification>|<collector-specification>
6 },
7 "searchBefore": "<base64-encoded-token>",
8 "sort": {
9 "score": {
10 "$meta": "searchScore"
11 }
12 },
13 ...
14 },
15 "$project": {
16 "paginationToken" : { "$meta" : "searchSequenceToken" }
17 },
18 ...
19}]

MongoDB Search returns documents in the results preceding the specified token in reverse order. MongoDB Search also returns the generated tokens for the documents in the results because you specified the searchSequenceToken in the $project stage after the $search stage (as shown in line 11). These tokens can be used as a reference point for another query with the same semantics.

The following examples use the db.collection.aggregate() method to run $search queries against the sample_mflix database. The first example query demonstrates how to retrieve a point of reference, which you use in the subsequent example queries to retrieve additional results for pages after or before the reference point.

To run these example queries in mongosh:

  1. Load the sample_mflix.movies collection

  2. 動的マッピングを使用して pagination-tutorialインデックスを作成します。インデックスの作成方法については、「MongoDB Search インデックスの管理」を参照してください。

  3. Connect to your cluster using mongosh and switch to the sample_mflix database

注意

デフォルトでは 、 MongoDB Search は結果内のドキュメントを、ドキュメントの関連性スコアでソートします。結果内の複数のドキュメントのスコアが同じである場合、 MongoDB Search は任意の順序付けられた結果を返します。特定の順序でドキュメントを返すには、クエリで一意のフィールドreleased を指定して結果をソートします。

最初のページの結果を検索し、後続のクエリのためのトークンまたは参照点を検索します。

サンプル クエリでは、次のパイプライン ステージを使用して最初のページの結果を取得し、後続のクエリのトークンまたは参照点を取得します。

パイプラインステージ
説明
  • テキスト演算子を使用して、 titleフィールドにsummerを含むタイトルを検索します。

  • 並べ替えオプションを使用して、 releasedフィールド値で結果を昇順に並べ替えます。

結果を10ドキュメントに制限します。

ドキュメントのtitlereleasedgenresフィールドのみが結果に含まれます。 このクエリは、結果内の各ドキュメントに次のフィールドも追加します。

  • paginationTokenは、後続のクエリで参照点として使用できるトークンです。

  • scoreは、結果内のドキュメントの関連性スコアです

db.movies.aggregate([
{
"$search": {
"index": "pagination-tutorial",
"text": {
"path": "title",
"query": "summer"
},
"sort": { "released": 1 }
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"paginationToken": { "$meta" : "searchSequenceToken" },
"score": { "$meta": "searchScore" }
}
}
])
[
{
genres: [ 'Drama' ],
title: "A Summer at Grandpa's",
paginationToken: 'CKUdGgJgAA==',
score: 2.262615203857422
},
{
genres: [ 'Musical', 'Romance' ],
title: 'Summer Stock',
released: ISODate('1951-01-22T00:00:00.000Z'),
paginationToken: 'CJsFGgkpAHw/0HT///8=',
score: 3.000213623046875
},
{
genres: [ 'Comedy', 'Romance' ],
title: 'Smiles of a Summer Night',
released: ISODate('1957-12-23T00:00:00.000Z'),
paginationToken: 'CKIHGgkpAKDlpaf///8=',
score: 2.0149309635162354
},
{
genres: [ 'Drama' ],
title: 'Violent Summer',
released: ISODate('1959-11-13T00:00:00.000Z'),
paginationToken: 'CI8JGgkpAJhJh7X///8=',
score: 3.000213623046875
},
{
genres: [ 'Drama', 'Romance' ],
title: 'A Summer Place',
released: ISODate('1959-11-18T00:00:00.000Z'),
paginationToken: 'CLoJGgkpAGQJobX///8=',
score: 2.579726457595825
},
{
genres: [ 'Drama' ],
title: 'The End of Summer',
released: ISODate('1962-02-01T00:00:00.000Z'),
paginationToken: 'CK0KGgkpAAzP18X///8=',
score: 2.262615203857422
},
{
genres: [ 'Drama', 'Romance' ],
title: 'Summer and Smoke',
released: ISODate('1962-04-01T00:00:00.000Z'),
paginationToken: 'CMQKGgkpAECmB8f///8=',
score: 2.579726457595825
},
{
genres: [ 'Documentary', 'Sport' ],
title: 'The Endless Summer',
released: ISODate('1968-08-17T00:00:00.000Z'),
paginationToken: 'CO4MGgkpAJjH5vX///8=',
score: 2.579726457595825
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: "Summer of '42",
released: ISODate('1971-04-09T00:00:00.000Z'),
paginationToken: 'CPQQGgkpAGRgUAkAAAA=',
score: 2.579726457595825
},
{
genres: [ 'Drama' ],
title: 'That Certain Summer',
released: ISODate('1972-11-01T00:00:00.000Z'),
paginationToken: 'COwRGgkpAPQV0hQAAAA=',
score: 2.579726457595825
}
]

注意

検索結果をカウントする

ページ分割中に検索結果をカウントするには、$searchMeta クエリを実行し、count オプションを使用します。これにより、検索条件に一致するドキュメントの総数を含むメタデータドキュメントが返されます。

次のサンプルクエリは、titleフィールド内の summer期間を持つドキュメントの合計数を取得します。

db.movies.aggregate([
{
"$searchMeta": {
"index": "pagination-tutorial",
"text": {
"path": "title",
"query": "summer"
},
"count": {
"type": "lowerBound",
"threshold": 5000
}
}
}
])
[ { count: { lowerBound: Long("65") } } ]

結果を検索して、アプリケーションに「次のページ」のような機能を構築します。

追加の結果を検索するには、結果を検索したい時点より後の参照点を指定します。

サンプル クエリでは、次のパイプライン ステージを使用して、同じタームの前のクエリからsearchSequenceTokenによって生成されたトークンを使用して、2 ページの結果を検索します。

パイプラインステージ
説明
  • テキスト演算子を使用して、 titleフィールドにsummerを含むタイトルを検索します。

  • Returns documents after the tenth document in the results by using the searchAfter option with the pagination token associated with the tenth document in the results of the query you the query you ran to Retrieve Page 1 and Generate Pagination Tokens.

  • 並べ替えオプションを使用して、 releasedフィールド値で結果を昇順に並べ替えます。

結果を10ドキュメントに制限します。

ドキュメントのtitlereleasedgenresフィールドのみが結果に含まれます。 また、結果内の各ドキュメントに次のフィールドも追加されます。

  • paginationTokenは、後続のクエリで参照点として使用できるトークンです。

  • scoreは、結果内のドキュメントの関連性スコアです

db.movies.aggregate([
{
"$search": {
"index": "pagination-tutorial",
"text": {
"path": "title",
"query": "summer"
},
"searchAfter": "COwRGgkpAPQV0hQAAAA=",
"sort": { "released": 1 }
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"paginationToken" : { "$meta" : "searchSequenceToken" },
"score": { "$meta": "searchScore" }
}
}
])
[
{
genres: [ 'Drama' ],
title: 'Summer Wishes, Winter Dreams',
released: ISODate('1974-09-09T00:00:00.000Z'),
paginationToken: 'CMwSGgkpAECHcCIAAAA=',
score: 2.262615203857422
},
{
genres: [ 'Drama', 'Thriller' ],
title: 'Shadows of a Hot Summer',
released: ISODate('1978-09-01T00:00:00.000Z'),
paginationToken: 'CPEVGgkpAGw/qz8AAAA=',
score: 2.0149309635162354
},
{
genres: [ 'Drama' ],
title: 'Indian Summer',
released: ISODate('1978-11-01T00:00:00.000Z'),
paginationToken: 'CNYRGgkpAFhj5UAAAAA=',
score: 3.000213623046875
},
{
genres: [ 'Drama' ],
title: 'Indian Summer',
released: ISODate('1978-11-01T00:00:00.000Z'),
paginationToken: 'CNsRGgkpAFhj5UAAAAA=',
score: 3.000213623046875
},
{
genres: [ 'Drama', 'Mystery' ],
title: 'One Deadly Summer',
released: ISODate('1983-05-11T00:00:00.000Z'),
paginationToken: 'COwcGgkpAAjtIGIAAAA=',
score: 2.579726457595825
},
{
genres: [ 'Comedy' ],
title: 'Summer Rental',
released: ISODate('1985-08-09T00:00:00.000Z'),
paginationToken: 'CL8fGgkpABTypHIAAAA=',
score: 3.000213623046875
},
{
genres: [ 'Drama', 'Romance' ],
title: 'Summer',
released: ISODate('1986-08-29T00:00:00.000Z'),
paginationToken: 'CO0gGgkpAHCiY3oAAAA=',
score: 3.5844719409942627
},
{
genres: [ 'Drama', 'Thriller' ],
title: 'Summer Camp Nightmare',
released: ISODate('1987-04-17T00:00:00.000Z'),
paginationToken: 'CNkiGgkpAHQ/CX8AAAA=',
score: 2.579726457595825
},
{
genres: [ 'Action', 'Crime', 'Drama' ],
title: 'Cold Summer of 1953',
released: ISODate('1988-06-01T00:00:00.000Z'),
paginationToken: 'CNsjGgkpACjVTYcAAAA=',
score: 2.262615203857422
},
{
genres: [ 'Drama', 'War' ],
title: 'That Summer of White Roses',
released: ISODate('1989-07-11T00:00:00.000Z'),
paginationToken: 'CI0mGgkpALSEc48AAAA=',
score: 2.0149309635162354
}
]

結果を検索して、アプリケーションに「前のページ」のような機能を構築します。

以前の結果を検索するには、結果を検索したい時点より前の参照点を指定します。

このサンプル クエリでは、次のパイプライン ステージを使用して、前のクエリで同じタームのsearchSequenceTokenによって生成されたトークンを使用して、最初のページの 結果を返します。

パイプラインステージ
説明
  • テキスト演算子を使用して、 titleフィールドにsummerを含むタイトルを検索します。

  • Returns documents 1 to 10 in the MongoDB Search results by using the searchBefore option with the pagination token associated with the eleventh document in the results of the query you ran to Retrieve Page 2 Using searchAfter.

  • 並べ替えオプションを使用して、 releasedフィールド値で結果を昇順に並べ替えます。

結果を10ドキュメントに制限します。

ドキュメントのtitlereleasedgenresフィールドのみが結果に含まれます。 また、結果内の各ドキュメントに次のフィールドも追加されます。

  • paginationTokenは、後続のクエリで参照点として使用できるトークンです。

  • scoreは、結果内のドキュメントの関連性スコアです

注意

By default, MongoDB Search returns the results in reverse order for queries that specify tokens to retrieve results before a point of reference. To return documents in-order, the query uses the toArray() and the JavaScript reverse() methods.

db.movies.aggregate([
{
"$search": {
"index": "pagination-tutorial",
"text": {
"path": "title",
"query": "summer"
},
"searchBefore": "CMwSGgkpAECHcCIAAAA=",
"sort": { "released": 1 }
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"paginationToken" : { "$meta" : "searchSequenceToken" },
"score": { "$meta": "searchScore" }
}
}
]).toArray().reverse()
[
{
genres: [ 'Drama' ],
title: "A Summer at Grandpa's",
paginationToken: 'CKUdGgJgAA==',
score: 2.262615203857422
},
{
genres: [ 'Musical', 'Romance' ],
title: 'Summer Stock',
released: ISODate('1951-01-22T00:00:00.000Z'),
paginationToken: 'CJsFGgkpAHw/0HT///8=',
score: 3.000213623046875
},
{
genres: [ 'Comedy', 'Romance' ],
title: 'Smiles of a Summer Night',
released: ISODate('1957-12-23T00:00:00.000Z'),
paginationToken: 'CKIHGgkpAKDlpaf///8=',
score: 2.0149309635162354
},
{
genres: [ 'Drama' ],
title: 'Violent Summer',
released: ISODate('1959-11-13T00:00:00.000Z'),
paginationToken: 'CI8JGgkpAJhJh7X///8=',
score: 3.000213623046875
},
{
genres: [ 'Drama', 'Romance' ],
title: 'A Summer Place',
released: ISODate('1959-11-18T00:00:00.000Z'),
paginationToken: 'CLoJGgkpAGQJobX///8=',
score: 2.579726457595825
},
{
genres: [ 'Drama' ],
title: 'The End of Summer',
released: ISODate('1962-02-01T00:00:00.000Z'),
paginationToken: 'CK0KGgkpAAzP18X///8=',
score: 2.262615203857422
},
{
genres: [ 'Drama', 'Romance' ],
title: 'Summer and Smoke',
released: ISODate('1962-04-01T00:00:00.000Z'),
paginationToken: 'CMQKGgkpAECmB8f///8=',
score: 2.579726457595825
},
{
genres: [ 'Documentary', 'Sport' ],
title: 'The Endless Summer',
released: ISODate('1968-08-17T00:00:00.000Z'),
paginationToken: 'CO4MGgkpAJjH5vX///8=',
score: 2.579726457595825
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: "Summer of '42",
released: ISODate('1971-04-09T00:00:00.000Z'),
paginationToken: 'CPQQGgkpAGRgUAkAAAA=',
score: 2.579726457595825
},
{
genres: [ 'Drama' ],
title: 'That Certain Summer',
released: ISODate('1972-11-01T00:00:00.000Z'),
paginationToken: 'COwRGgkpAPQV0hQAAAA=',
score: 2.579726457595825
}
]

結果を検索して、アプリケーションでページスキップを可能にする機能を構築します。

結果をスキップして 2 ページから 5 ページへジャンプするには、searchSequenceToken が生成するトークンを使用して、結果を取得する基準点を指定し、その後、結果で 20 件のドキュメントをスキップします。

The sample query uses the following pipeline stages to jump to results on page 5 by using the token generated by searchSequenceToken from the prior query for the same term and by using the $skip and $limit stages:

パイプラインステージ
説明
  • テキスト演算子を使用して、 titleフィールドにsummerを含むタイトルを検索します。

  • 並べ替えオプションを使用して、 releasedフィールド値で結果を昇順に並べ替えます。

  • Returns documents after the twentieth document specified by using the pagination token generated by the query you ran to Retrieve Page 2 Using searchAfter.

Skips 20 documents in the results after the specified point of reference, which is the token associated with the twentieth document in the results for the query you ran to Retrieve Page 2 Using searchAfter.

結果を10ドキュメントに制限します。

ドキュメントのtitlereleasedgenresフィールドのみが結果に含まれます。 また、結果内の各ドキュメントに次のフィールドも追加されます。

  • paginationTokenは、後続のクエリで参照点として使用できるトークンです。

  • scoreは、結果内のドキュメントの関連性スコアです

db.movies.aggregate([
{
"$search": {
"index": "pagination-tutorial",
"text": {
"path": "title",
"query": "summer"
},
"searchAfter": "COwRGgkpAPQV0hQAAAA=",
"sort": { "released": 1 }
}
},
{
"$skip": 20
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"paginationToken" : { "$meta" : "searchSequenceToken" },
"score": { "$meta": "searchScore" }
}
}
])
[
{
genres: [ 'Drama' ],
title: 'A Storm in Summer',
released: ISODate('2000-02-27T00:00:00.000Z'),
paginationToken: 'CO5FGgkpAChakN0AAAA=',
score: 2.262615203857422
},
{
genres: [ 'Comedy', 'Romance' ],
title: 'Wet Hot American Summer',
released: ISODate('2002-04-11T00:00:00.000Z'),
paginationToken: 'CKtIGgkpAFBUIu0AAAA=',
score: 2.262615203857422
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: 'Summer Things',
released: ISODate('2002-10-09T00:00:00.000Z'),
paginationToken: 'CIpPGgkpAFxzxvAAAAA=',
score: 3.000213623046875
},
{
genres: [ 'Adventure', 'Drama', 'Family' ],
title: 'Wolf Summer',
released: ISODate('2003-02-28T00:00:00.000Z'),
paginationToken: 'COZWGgkpAGS6ofMAAAA=',
score: 3.000213623046875
},
{
genres: [ 'Animation', 'Adventure' ],
title: 'Nasu: Summer in Andalusia',
released: ISODate('2003-06-26T00:00:00.000Z'),
paginationToken: 'CNlaGgkpAMxoAfYAAAA=',
score: 2.262615203857422
},
{
genres: [ 'Drama' ],
title: 'Spring, Summer, Fall, Winter... and Spring',
released: ISODate('2004-05-28T00:00:00.000Z'),
paginationToken: 'CJ5ZGgkpAOjnyPwAAAA=',
score: 1.8161234855651855
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: 'Summer Storm',
released: ISODate('2004-09-02T00:00:00.000Z'),
paginationToken: 'CMVfGgkpAMRwvP4AAAA=',
score: 3.000213623046875
},
{
genres: [ 'Drama' ],
title: 'Summer in the Golden Valley',
released: ISODate('2004-10-08T00:00:00.000Z'),
paginationToken: 'CNNWGgkpALTVdf8AAAA=',
score: 2.0149309635162354
},
{
genres: [ 'Drama', 'Romance' ],
title: 'My Summer of Love',
released: ISODate('2005-07-01T00:00:00.000Z'),
paginationToken: 'CL5aGgkpAEyxzwQBAAA=',
score: 2.262615203857422
},
{
genres: [ 'Drama' ],
title: 'Summer in Berlin',
released: ISODate('2006-01-05T00:00:00.000Z'),
paginationToken: 'CPZmGgkpANzclwgBAAA=',
score: 2.579726457595825
}
]

MongoDB Search ファセット では searchSequenceToken を使用します。

MongoDB Search facet(MongoDB Search 演算子)を使用して結果をグループ化するには、すべての stringフィールドをtoken タイプとしてインデックス必要があります。次のクエリを実行し、moviesコレクションの genresフィールドで結果をグループ化するには、インデックスが次の例のようになっている必要があります。

{
"mappings": {
"dynamic": true,
"fields": {
"genres": {
"type": "token"
}
}
}
}
}

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

パイプラインステージ
説明
  • facet(MongoDB検索演算子)コレクターを使用して、titleフィールドに summer を含むタイトルを検索します。

  • facetsオプションを使用して、各ジャンルの結果内の映画の合計数を検索します。

Adds the paginationToken field to store the tokens for each document in the results generated by using the searchSequenceToken option.

結果を10ドキュメントに制限します。

次のフィールドを返します。

  • docs フィールド。これには結果内のドキュメントのtitlereleasedgenresフィールドとpaginationTokenフィールドのみが含まれます。

  • meta フィールド。これには、 $$SEARCH_META変数に保存されている各ジャンルの結果内の映画の総数が含まれます。

db.movies.aggregate([
{
"$search": {
"index": "pagination-tutorial",
"facet": {
"operator": {
"text": {
"path": "title",
"query": "summer"
}
},
"facets": {
"genresFacet": {
"type": "string",
"path": "genres"
}
}
}
}
},
{
"$addFields": {
"paginationToken" : { "$meta" : "searchSequenceToken" }
}
},
{ "$limit": 10 },
{
"$facet": {
"docs": [
{ "$project":
{
"_id": 0,
"title": 1,
"released": 1,
"genres": 1,
"paginationToken" : 1
}
}
],
"meta": [
{ "$replaceWith": "$$SEARCH_META" },
{ "$limit": 1 }
]
}
},
{
"$set": {
"meta": {
"$arrayElemAt": ["$meta", 0]
}
}
}
])
[
{
docs: [
{
genres: [ 'Drama', 'Romance' ],
title: 'Summer',
released: ISODate('1986-08-29T00:00:00.000Z'),
paginationToken: 'CO0gFf1nZUA='
},
{
genres: [ 'Musical', 'Romance' ],
title: 'Summer Stock',
released: ISODate('1951-01-22T00:00:00.000Z'),
paginationToken: 'CJsFFYADQEA='
},
{
genres: [ 'Drama' ],
title: 'Violent Summer',
released: ISODate('1959-11-13T00:00:00.000Z'),
paginationToken: 'CI8JFYADQEA='
},
{
genres: [ 'Drama' ],
title: 'Indian Summer',
released: ISODate('1978-11-01T00:00:00.000Z'),
paginationToken: 'CNYRFYADQEA='
},
{
genres: [ 'Drama' ],
title: 'Indian Summer',
released: ISODate('1978-11-01T00:00:00.000Z'),
paginationToken: 'CNsRFYADQEA='
},
{
genres: [ 'Comedy' ],
title: 'Summer Rental',
released: ISODate('1985-08-09T00:00:00.000Z'),
paginationToken: 'CL8fFYADQEA='
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: 'Summer Things',
released: ISODate('2002-10-09T00:00:00.000Z'),
paginationToken: 'CIpPFYADQEA='
},
{
genres: [ 'Adventure', 'Drama', 'Family' ],
title: 'Wolf Summer',
released: ISODate('2003-02-28T00:00:00.000Z'),
paginationToken: 'COZWFYADQEA='
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: 'Summer Storm',
released: ISODate('2004-09-02T00:00:00.000Z'),
paginationToken: 'CMVfFYADQEA='
},
{
genres: [ 'Drama', 'Romance' ],
title: 'Summer Palace',
released: ISODate('2007-04-18T00:00:00.000Z'),
paginationToken: 'CIRrFYADQEA='
}
],
meta: {
count: { lowerBound: Long('65') },
facet: {
genresFacet: {
buckets: [
{ _id: 'Drama', count: Long('48') },
{ _id: 'Romance', count: Long('20') },
{ _id: 'Comedy', count: Long('19') },
{ _id: 'Family', count: Long('7') },
{ _id: 'Adventure', count: Long('5') },
{ _id: 'Crime', count: Long('5') },
{ _id: 'Mystery', count: Long('5') },
{ _id: 'Thriller', count: Long('5') },
{ _id: 'Horror', count: Long('4') },
{ _id: 'Action', count: Long('3') }
]
}
}
}
}
]