Docs Menu
Docs Home
/
Atlas
/ / / /

Atlas Search 結果のソート

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

  • boolean

  • date

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

  • objectId

  • uuid

  • stringトークンタイプとしてインデックス付け)

結果内のドキュメントのスコアでソートしたり、 null 値でソートしたりすることもできます。

Atlas は、メジャーおよびマイナーなMongoDB 5.0 以降のすべてのバージョンで非シャーディングされたソート クエリをサポートしています。シャーディングされたソート クエリは、6.0 のすべてのメジャー リリースと、7.0 以降のバージョンのすべてのメジャー リリースとマイナー リリースで利用できます。

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

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

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

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

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

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

sortオプションには、並べ替えるフィールドとそれぞれの並べ替え順序を指定するドキュメントが指定されます。 Atlas Search は、サポートされているデータ型のMongoDB 比較順序に従います。 UUID 値はBinDataのように扱われます。 詳細については、存在しないフィールドを参照してください。

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

1

昇順でソートします。

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

-1

降順でソートします。

スコアの昇順または降順で並べ替えることもできます。 sortオプションには$meta式を指定するドキュメントが指定されます。これにはsearchScore値が必要です。

アプリケーションで、ユーザーが検索結果の最後のページにスキップできるとします。 次の例では、結果をスコアの昇順でソートし、スコアが最も低いドキュメントが結果の上部に表示されるようにします。

sort: {score: {$meta: "searchScore", order: 1}}

sortを使用すると、結果内の複数のドキュメントのスコアが同じである場合に、結果の順序が特定の順序になるようにすることもできます。 たとえば、次の例に示すように、 lastUpdatedという名前の日付フィールドなど、一意のフィールドで結果をソートすると、Atlas Search は決定された順序で同じスコアを持つ結果を返します。

sort: {score: {$meta: "searchScore"}, lastUpdated: 1}

ただし、結果を並べ替えるための一意のフィールドを指定しない場合、Atlas Search はスコアの降順で並べ替えられた結果を返します。 Atlas Search では、スコアまたは値が同一の結果が任意の順序で返されます。 次の例では、結果を一意のフィールドでソートしません。

sort: {score: {$meta: "searchScore"}}

詳細については、「 結果内のドキュメントにスコアを付ける 」を参照してください。

Atlas Search は、ソート用に配列をフラット化します。

次の配列について考えてみましょう。

[4, [1, [8,5], 9], 2]

Atlas Search は、次のように、前述の配列をフラット化します。

4, 1, 8, 5, 9, 2

昇順 並べ替えでは、Atlas Search は1を使用して配列を他の値と比較します。 降順並べ替えでは、Atlas Search は9を使用して配列を他の値と比較します。

配列内の要素と比較する場合:

  • 昇順ソートでは、Atlas Search は配列の最小要素を比較するか、( < )未満の比較を実行します。

    Atlas Search では、数値で昇順にソートすると、次の順序で結果がソートされます。

    -20
    [-3, 12] // <- -3 comes before 5.
    5
    [6, 18] // <- 6 comes after 5.
    13
    14
  • 降順ソートでは、Atlas Search は配列の最大要素を比較するか、 より大きい( > )比較を実行します。

    Atlas Search では、数値で降順にソートすると、次の順序で結果がソートされます。

    [6, 18] // <- 18 comes before 14.
    14
    13
    [-3, 12] // <- 12 comes after 13.
    5
    -20

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

  • 昇順 ソートの場合、Atlas Search はBSON型の最も低い要素を使用します。

  • 降順ソートの場合、Atlas Search はBSON type の最も高い要素を使用します。

配列内に同じBSON type の値が複数ある場合、選択したタイプの標準ソート動作が適用されます。

次の配列について考えてみましょう。

[ 'foo', null, 15, true, false ]
  • 昇順 並べ替え の場合、Atlas Searchnull はサポートされている最低のBSONタイプであるため、 を使用します。

  • 降順並べ替えでは、Atlas Search はtrue を使用します。これは配列内で最も高いBSON型であり、Atlas Search はtrue 値よりも大きいfalse 値をランク付けします。

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

  • 昇順 ソートの場合、Atlas Search は15 を使用します。これは配列の最低のBSONタイプになっているためです。

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

詳細については、「 Null および欠損値によるソート 」を参照してください。

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

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

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

結果に null 値が表示される場所を設定するには、noData sort構文で フィールドを指定します。noDataフィールドは次の値を取ります。

  • lowest (デフォルト): ソート中に null 値を最小のBSONタイプとして設定します。昇順ソートでは null 値を結果の上部に、降順ソートでは最下位でソートします。

  • highest: ソート時に null 値を最上位のBSONタイプとして設定します。昇順ソートでは null 値を結果の下にソートし、降順ソートでは null 値を上部にソートします。

注意

同じ動作は、null または欠落値を含む複数のタイプを持つ配列をソートする場合にも適用されます。

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

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

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

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

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

Atlas Search インデックスは 結果整合性があり、結果として返される値はソートで使用される値と異なる場合があります。

この機能により、後続の ステージとして$search$limit とともに使用するクエリが最適化されます。Atlas Search がコレクション内のすべてのドキュメントをソートする必要がある場合、応答が遅くなる可能性があります。

Atlas 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

任意。 検索スコアでソートするかどうかを決定します。 詳しくは、「 スコアと一意のフィールドで並べ替える 」を参照してください。

<field-to-sort>

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

<sort-order>

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

noDataフィールドを指定する場合は、次の構文のドキュメントを使用します。

"<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フィールドは次のようになります。

    • number ファセット クエリの実行を含む、ソートおよびクエリのタイプ

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

    • date ファセット クエリの実行を含む、ソートおよびクエリのタイプ

  • インデックス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}

上記のインデックス定義では、Atlas 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}

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

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

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

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

    注意

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

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

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

  • $limitステージを使用して、出力を5の結果に制限します。

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

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

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

1

次のクエリをコピーして Query Editor に貼り付け、Query EditorSearch ボタンをクリックします。

[
{
$search: {
"compound": {
"filter": [{
"wildcard": {
"query": "Summer*",
"path": "title"
}
}],
"must": [{
"near": {
"pivot": 13149000000,
"path": "released",
"origin": ISODate("2014-04-18T00:00:00.000+00:00")
}
}]
},
"sort": {
"released": -1,
"title": 1
}
}
}
]
SCORE: 0.348105788230896 _id: "573a13f0f29313caabddaf7a"
countries: Array
runtime: 104
cast: Array
...
title: "Summer Nights"
...
released: 2015-01-28T00:00:00.000+00:00
...
SCORE: 0.5917375683784485 _id: "573a13e6f29313caabdc673b"
plot: "25-year-old Iiris and Karoliina have been best friends since childhood…"
genres: Array
runtime: 90
...
title: "Summertime"
...
released: 2014-08-01T00:00:00.000+00:00
...
SCORE: 0.9934720396995544 _id: "573a13eff29313caabdd760c"
plot: "Erik Sparrow is one of the lucky ones. He's got a good job. He's in a …"
genres: Array
runtime: 86
...
title: "Summer of Blood"
...
released: 2014-04-17T00:00:00.000+00:00
...
SCORE: 0.15982933342456818 _id: "573a13cff29313caabd8ab74"
plot: "The story of an adult and a teenage couple during a brief summer holid…"
genres: Array
countries: Array
...
title: "Summer Games"
...
released: 2012-02-08T00:00:00.000+00:00
...
SCORE: 0.13038821518421173 _id: "573a13cef29313caabd87f4e"
plot: "Summer of Goliath is a documentary/fiction hybrid that narrates variou…"
genres: Array
runtime: 78
...
title: "Summer of Goliath"
...
released: 2011-07-08T00:00:00.000+00:00
...
SCORE: 0.08124520629644394 _id: "573a13c7f29313caabd7608d"
plot: "A student tries to fix a problem he accidentally caused in OZ, a digit…"
genres: Array
runtime: 114
...
title: "Summer Wars"
...
released: 2009-08-01T00:00:00.000+00:00
SCORE: 0.0711759403347969 _id: "573a13bbf29313caabd54ee6"
plot: "The life of a public school epitomized by disobedient student Jonah Ta…"
genres: Array
runtime: 30
...
title: "Summer Heights High"
...
released: 2008-11-09T00:00:00.000+00:00
...
SCORE: 0.06951779872179031 _id: "573a13bff29313caabd5f935"
plot: "On his spring break at the seaside, with his wife and his four year ol…"
genres: Array
runtime: 102
...
title: "Summer Holiday"
...
released: 2008-09-19T00:00:00.000+00:00
...
SCORE: 0.05834990739822388 _id: "573a13c0f29313caabd628ac"
plot: "Kochi Uehara is a fourth grade student living in the suburb of Tokyo. …"
genres: Array
runtime: 138
...
title: "Summer Days with Coo"
...
released: 2007-07-28T00:00:00.000+00:00
...
SCORE: 0.056174591183662415 _id: "573a13b8f29313caabd4c1d0"
fullplot: "Country girl Yu Hong leaves her village, her family and her lover to s…"
genres: Array
runtime: 158
...
title: "Summer Palace"
...
released: 2007-04-18T00:00:00.000+00:00
...
2

Search Tester では、返されるドキュメント内のすべてのフィールドが表示されない場合があります。クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。

でクエリを実行するにはmongosh

1db.movies.aggregate([
2{
3 $search: {
4 "index": "default",
5 "compound": {
6 "filter": [{
7 "wildcard": {
8 "query": "Summer*",
9 "path": "title"
10 }
11 }],
12 "must": [{
13 "near": {
14 "pivot": 13149000000,
15 "path": "released",
16 "origin": ISODate("2014-04-18T00:00:00.000+00:00")
17 }
18 }]
19 },
20 "sort": {
21 "released": -1
22 }
23 }
24},
25{
26 $limit: 5
27},
28{
29 $project: {
30 "_id": 0,
31 "title": 1,
32 "released": 1,
33 "score": {
34 "$meta": "searchScore"
35 }
36 }
37}])
[
{
title: 'Summer Nights',
released: ISODate("2015-01-28T00:00:00.000Z"),
score: 0.348105788230896
},
{
title: 'Summertime',
released: ISODate("2014-08-01T00:00:00.000Z"),
score: 0.5917375683784485
},
{
title: 'Summer of Blood',
released: ISODate("2014-04-17T00:00:00.000Z"),
score: 0.9934720396995544
},
{
title: 'Summer Games',
released: ISODate("2012-02-08T00:00:00.000Z"),
score: 0.15982933342456818
},
{
title: 'Summer of Goliath',
released: ISODate("2011-07-08T00:00:00.000Z"),
score: 0.13038821518421173
}
]

MongoDB Compassでは、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプラインステージを構成します。ステージを追加するには、Add Stage をクリックします。

パイプラインステージ
クエリ

$search

{
"index": "default",
"compound": {
"filter": [{
"wildcard": {
"query": "Summer*",
"path": "title"
}
}],
"must": [{
"near": {
"pivot": 13149000000,
"path": "released",
"origin": ISODate("2014-04-18T00:00:00.000+00:00")
}
}]
},
"sort": {
"released": -1
}
}

$limit

5

$project

{
_id: 0,
title: 1,
released: 1,
score: { $meta: "searchScore" }
}

Auto Previewを有効にした場合、MongoDB Compass は$limitパイプライン ステージの横に次のドキュメントを表示します。

{
title: 'Summer Nights',
released: 2015-01-28T00:00:00.000+00:00,
score: 0.348105788230896
},
{
title: 'Summertime',
released: 2014-08-01T00:00:00.000+00:00,
score: 0.5917375683784485
},
{
title: 'Summer of Blood',
released: 2014-04-17T00:00:00.000+00:00,
score: 0.9934720396995544
},
{
title: 'Summer Games',
released: 2012-02-08T00:00:00.000+00:00,
score: 0.15982933342456818
},
{
title: 'Summer of Goliath',
released: 2011-07-08T00:00:00.000+00:00,
score: 0.13038821518421173
}
1
  1. Program.cs ファイルの内容を、次のコードで置き換えます。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class SortByStrings
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22
    23 // declare data for compound query
    24 var originDate = new DateTime(2014, 04, 18, 0, 0, 0, DateTimeKind.Utc);
    25
    26 // define search options
    27 var searchOptions = new SearchOptions<MovieDocument>()
    28 {
    29 Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released),
    30 IndexName = "default"
    31 };
    32
    33 // define and run pipeline
    34 var results = moviesCollection.Aggregate()
    35 .Search(Builders<MovieDocument>.Search.Compound()
    36 .Filter(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Summer*"))
    37 .Must(Builders<MovieDocument>.Search.Near(movie => movie.Released, originDate, 13149000000)), searchOptions)
    38 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    39 .Include(movie => movie.Released)
    40 .Include(movie => movie.Title)
    41 .Exclude(movie => movie.Id)
    42 .MetaSearchScore(movie => movie.Score))
    43 .Limit(5)
    44 .ToList();
    45
    46 // print results
    47 foreach (var movie in results)
    48 {
    49 Console.WriteLine(movie.ToJson());
    50 }
    51 }
    52}
    53
    54[BsonIgnoreExtraElements]
    55public class MovieDocument
    56{
    57 [BsonIgnoreIfDefault]
    58 public ObjectId Id { get; set; }
    59 public DateTime Released { get; set; }
    60 public string Title { get; set; }
    61 public double Score { get; set; }
    62}
  2. <connection-string>を指定します。

2
dotnet run Program.cs
{ "released" : ISODate("2015-01-28T00:00:00Z"), "title" : "Summer Nights", "score" : 0.348105788230896 }
{ "released" : ISODate("2014-08-01T00:00:00Z"), "title" : "Summertime", "score" : 0.59173756837844849 }
{ "released" : ISODate("2014-04-17T00:00:00Z"), "title" : "Summer of Blood", "score" : 0.99347203969955444 }
{ "released" : ISODate("2014-01-17T00:00:00Z"), "title" : "Summer in February", "score" : 0.62580311298370361 }
{ "released" : ISODate("2012-02-08T00:00:00Z"), "title" : "Summer Games", "score" : 0.15982933342456818 }
1
  1. sort-by-date.go という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(options.Client().ApplyURI("<connection-string"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{Key: "$search", Value: bson.M{
    26 "index": "default",
    27 "compound": bson.M{
    28 "filter": bson.A{
    29 bson.M{
    30 "wildcard": bson.D{
    31 {Key: "path", Value: "title"},
    32 {Key: "query", Value: "Summer*"},
    33 }},
    34 },
    35 "must": bson.A{
    36 bson.M{
    37 "near": bson.M{
    38 "path": "released",
    39 "origin": time.Date(2014, time.April, 18, 0, 0, 0, 0, time.UTC),
    40 "pivot": 13149000000}},
    41 },
    42 },
    43 "sort": bson.D{{Key: "released", Value: -1}},
    44 }}}
    45
    46 limitStage := bson.D{{Key: "$limit", Value: 5}}
    47 projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "_id", Value: 0}, {Key: "title", Value: 1}, {Key: "released", Value: 1}, {Key: "score", Value: bson.D{{Key: "$meta", Value: "searchScore"}}}}}}
    48
    49 // run pipeline
    50 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
    51 if err != nil {
    52 panic(err)
    53 }
    54
    55 // print results
    56 var results []bson.D
    57 if err = cursor.All(context.TODO(), &results); err != nil {
    58 panic(err)
    59 }
    60 for _, result := range results {
    61 fmt.Println(result)
    62 }
    63}
  2. <connection-string>を指定します。

2
go run sort-by-date.go
[{title Summer Nights} {released 1422403200000} {score 0.348105788230896}]
[{title Summertime} {released 1406851200000} {score 0.5917375683784485}]
[{title Summer of Blood} {released 1397692800000} {score 0.9934720396995544}]
[{title Summer Games} {released 1328659200000} {score 0.15982933342456818}]
[{title Summer of Goliath} {released 1310083200000} {score 0.13038821518421173}]
1
  1. SortByDate.java という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13import java.time.Instant;
    14import java.util.Date;
    15
    16public class SortByDate {
    17 public static void main( String[] args ) {
    18 // define query
    19 Document agg =
    20 new Document("$search",
    21 new Document("index", "default")
    22 .append("compound",
    23 new Document("filter", Arrays.asList(new Document("wildcard",
    24 new Document("query", "Summer*")
    25 .append("path", "title"))))
    26 .append("must", Arrays.asList(new Document("near",
    27 new Document("pivot", 13149000000L)
    28 .append("path", "released")
    29 .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00")))))))
    30 .append("sort", new Document("released", -1)));
    31
    32 // specify connection
    33 String uri = "<connection-string>";
    34
    35 // establish connection and set namespace
    36 try (MongoClient mongoClient = MongoClients.create(uri)) {
    37 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    38 MongoCollection<Document> collection = database.getCollection("movies");
    39 // run query and print results
    40 collection.aggregate(Arrays.asList(agg,
    41 limit(5),
    42 project(fields(exclude("_id"), include("title"), include("released"), computed("score", new Document("$meta", "searchScore"))))))
    43 .forEach(doc -> System.out.println(doc.toJson()));
    44 }
    45 }
    46}

    注意

    Maven 環境でサンプル コードを実行するには、 ファイルのインポート ステートメントの上に次のコードを追加します。

    package com.mongodb.drivers;
  2. <connection-string>を指定します。

2
javac SortByDate.java
java SortByDate
{"title": "Summer Nights", "released": {"$date": "2015-01-28T00:00:00Z"}, "score": 0.348105788230896}
{"title": "Summertime", "released": {"$date": "2014-08-01T00:00:00Z"}, "score": 0.5917375683784485}
{"title": "Summer of Blood", "released": {"$date": "2014-04-17T00:00:00Z"}, "score": 0.9934720396995544}
{"title": "Summer Games", "released": {"$date": "2012-02-08T00:00:00Z"}, "score": 0.15982933342456818}
{"title": "Summer of Goliath", "released": {"$date": "2011-07-08T00:00:00Z"}, "score": 0.13038821518421173}
1
  1. SortByDate.kt という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7import java.time.Instant
    8import java.util.*
    9
    10fun main() {
    11 // establish connection and set namespace
    12 val uri = "<connection-string>"
    13 val mongoClient = MongoClient.create(uri)
    14 val database = mongoClient.getDatabase("sample_mflix")
    15 val collection = database.getCollection<Document>("movies")
    16
    17 runBlocking {
    18 // define query
    19 val agg = Document(
    20 "\$search",
    21 Document("index", "default")
    22 .append(
    23 "compound",
    24 Document(
    25 "filter", listOf(
    26 Document(
    27 "wildcard",
    28 Document("query", "Summer*")
    29 .append("path", "title")
    30 )
    31 )
    32 )
    33 .append(
    34 "must", listOf(
    35 Document(
    36 "near",
    37 Document("pivot", 13149000000L)
    38 .append("path", "released")
    39 .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00")))
    40 )
    41 )
    42 )
    43 )
    44 .append("sort", Document("released", -1))
    45 )
    46
    47 // run query and print results
    48 val resultsFlow = collection.aggregate<Document>(
    49 listOf(
    50 agg,
    51 limit(5),
    52 project(fields(
    53 excludeId(),
    54 include("title", "released"),
    55 computed("score", Document("\$meta", "searchScore"))
    56 ))
    57 )
    58 )
    59 resultsFlow.collect { println(it) }
    60 }
    61 mongoClient.close()
    62}
  2. <connection-string>を指定します。

2
kotlin SortByDate.kt
Document{{title=Summer Nights, released=Tue Jan 27 19:00:00 EST 2015, score=0.348105788230896}}
Document{{title=Summertime, released=Thu Jul 31 20:00:00 EDT 2014, score=0.5917375683784485}}
Document{{title=Summer of Blood, released=Wed Apr 16 20:00:00 EDT 2014, score=0.9934720396995544}}
Document{{title=Summer Games, released=Tue Feb 07 19:00:00 EST 2012, score=0.15982933342456818}}
Document{{title=Summer of Goliath, released=Thu Jul 07 20:00:00 EDT 2011, score=0.13038821518421173}}
1
  1. sort-by-date.js という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1const { MongoClient } = require("mongodb");
    2
    3// Replace the uri string with your MongoDB deployments connection string.
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11 await client.connect();
    12
    13 // set namespace
    14 const database = client.db("sample_mflix");
    15 const coll = database.collection("movies");
    16
    17 // define pipeline
    18 const agg = [
    19 {$search: {
    20 index: "default",
    21 compound: {
    22 filter: {wildcard: {query: "Summer*", path: "title"}},
    23 must: [{near: {path: "released", origin: new Date("2014-04-18T00:00:00.000Z"), pivot: 13149000000}}]
    24 },
    25 sort: { released: -1 }
    26 }},
    27 {$limit: 5},
    28 {$project: {_id: 0, title: 1, released: 1, score: {$meta: "searchScore"}}}
    29 ];
    30
    31 // run pipeline
    32 const result = await coll.aggregate(agg);
    33
    34 // print results
    35 await result.forEach((doc) => console.log(doc));
    36
    37 } finally {
    38 await client.close();
    39 }
    40}
    41run().catch(console.dir);
  2. <connection-string>を指定します。

2
node sort-by-date.js
{
title: 'Summer Nights',
released: 2015-01-28T00:00:00.000Z,
score: 0.348105788230896
}
{
title: 'Summertime',
released: 2014-08-01T00:00:00.000Z,
score: 0.5917375683784485
}
{
title: 'Summer of Blood',
released: 2014-04-17T00:00:00.000Z,
score: 0.9934720396995544
}
{
title: 'Summer Games',
released: 2012-02-08T00:00:00.000Z,
score: 0.15982933342456818
}
{
title: 'Summer of Goliath',
released: 2011-07-08T00:00:00.000Z,
score: 0.13038821518421173
}
1
  1. sort-by-date.py という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1import datetime
    2import pymongo
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient('<connection-string>')
    6
    7# define pipeline
    8pipeline = [
    9 {'$search': {
    10 'index': 'default',
    11 'compound': {
    12 'filter': {'wildcard': {'query': 'Summer*', 'path': 'title'}},
    13 'must': {'near': {
    14 "path": "released",
    15 "origin": datetime.datetime(2014, 4, 18, 0, 0, 0, 0),
    16 "pivot": 13149000000
    17 }}},
    18 'sort': { 'released': -1 }}},
    19 {'$limit': 5},
    20 {'$project': {'_id': 0, 'title': 1, 'released': 1, 'score': {'$meta': 'searchScore'}}}
    21]
    22
    23# run pipeline
    24result = client['sample_mflix']['movies'].aggregate(pipeline)
    25
    26# print results
    27for i in result:
    28 print(i)
  2. <connection-string>を指定します。

2
python sort-by-date.py
{'title': 'Summer Nights', 'released': datetime.datetime(2015, 1, 28, 0, 0), 'score': 0.348105788230896}
{'title': 'Summertime', 'released': datetime.datetime(2014, 8, 1, 0, 0), 'score': 0.5917375683784485}
{'title': 'Summer of Blood', 'released': datetime.datetime(2014, 4, 17, 0, 0), 'score': 0.9934720396995544}
{'title': 'Summer Games', 'released': datetime.datetime(2012, 2, 8, 0, 0), 'score': 0.15982933342456818}
{'title': 'Summer of Goliath', 'released': datetime.datetime(2011, 7, 8, 0, 0), 'score': 0.13038821518421173}

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

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

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

  • $limitステージを使用して、出力を5の結果に制限します。

  • $projectステージでは、 titleawards.winsを除くすべてのフィールドが除外されます。

1

次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorSearchボタンをクリックします。

[
{
"$search": {
"range": {
"path": "awards.wins",
"gte": 10
},
"sort": {
"awards.wins": -1,
}
}
}
]
SCORE: 1 _id: "573a13d5f29313caabd9cae7"
fullplot: "Based on an incredible true story of one man's fight for survival and …"
imdb: Object
...
year: 2013
...
awards: Object
wins: 267
...
...
SCORE: 1 _id: "573a13c7f29313caabd74a4d"
fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…"
imdb: Object
...
year: 2013
...
awards: Object
wins: 231
...
...
SCORE: 1 _id: "573a13cbf29313caabd808d2"
fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…"
imdb: Object
...
year: 2013
...
awards: Object
wins: 231
...
...
SCORE: 1 _id: “573a13dff29313caabdb7adb”"
fullplot: "Actor Riggan Thomson is most famous for his movie role from over twent…"
imdb: Object
...
year: 2014
...
awards: Object
wins: 210
...
...
SCORE: 1 _id: "573a13bef29313caabd5c06c"
plot: "The life of Mason, from early childhood to his arrival at college."
imdb: Object
...
runtime: 165
...
awards: Object
wins: 185
...
...
SCORE: 1 _id: "573a139ef29313caabcfbd6a"
fullplot: "While Frodo & Sam continue to approach Mount Doom to destroy the One R…"
imdb: Object
...
year: 2003
...
awards: Object
wins: 175
...
...
SCORE: 1 _id: "573a13b5f29313caabd447f5"
plot: "In rural Texas, welder and hunter Llewelyn Moss discovers the remains …"
imdb: Object
...
year: 2007
...
awards: Object
wins: 172
...
...
SCORE: 1 _id: "573a13c3f29313caabd68d9f"
plot: "On a fall night in 2003, Harvard undergrad and computer programming ge…"
imdb: Object
...
year: 2010
...
awards: Object
wins: 171
...
...
SCORE: 1 _id: "573a13c5f29313caabd6ee61"
fullplot: "Dom Cobb is a skilled thief, the absolute best in the dangerous art of…"
imdb: Object
...
year: 2010
...
awards: Object
wins: 162
...
...
SCORE: 1 _id: "573a13bdf29313caabd58fd3"
plot: "The story of Jamal Malik, an 18 year-old orphan from the slums of Mumb…"
imdb: Object
...
year: 2008
...
awards: Object
wins: 161
...
...
2

Search Tester では、返されるドキュメント内のすべてのフィールドが表示されない場合があります。クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。

でクエリを実行するにはmongosh

1db.movies.aggregate([
2 {
3 "$search": {
4 "range": {
5 "path": "awards.wins",
6 "gte": 10
7 },
8 "sort": {
9 "awards.wins": -1,
10 }
11 }
12 },
13 {
14 $limit: 5
15 },
16 {
17 "$project": {
18 "_id": 0,
19 "title": 1,
20 "awards.wins": 1
21 }
22 }
23])
[
{
title: '12 Years a Slave',
awards: { wins: 267 }
},
{
title: 'Gravity',
awards: { wins: 231 }
},
{
title: 'Gravity',
awards: { wins: 231 }
},
{
title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
awards: { wins: 210 }
},
{
title: 'Boyhood',
awards: { wins: 185 }
}
]

MongoDB Compassでは、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプラインステージを構成します。ステージを追加するには、Add Stage をクリックします。

パイプラインステージ
クエリ

$search

{
index: "default",
"range": {
"path": "awards.wins",
"gte": 10
},
"sort": {
"awards.wins": -1,
}
}

$limit

5

$project

{
title: 1,
released: 1,
year: 1
}

Auto Previewを有効にした場合、MongoDB Compass は$limitパイプライン ステージの横に次のドキュメントを表示します。

[
{
title: '12 Years a Slave',
awards: { wins: 267 }
},
{
title: 'Gravity',
awards: { wins: 231 }
},
{
title: 'Gravity',
awards: { wins: 231 }
},
{
title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
awards: { wins: 210 }
},
{
title: 'Boyhood',
awards: { wins: 185 }
}
]
1
  1. プロジェクトで、Program.csファイルの内容を次のコードで置き換えます。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class SortByNumbers
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define search options
    23 var searchOptions = new SearchOptions<MovieDocument>()
    24 {
    25 Sort = Builders<MovieDocument>.Sort.Descending(movies => movies.Awards.Wins),
    26 IndexName = "default"
    27 };
    28
    29 // define and run pipeline
    30 var results = moviesCollection.Aggregate()
    31 .Search(
    32 Builders<MovieDocument>.Search.Range(movie => movie.Awards.Wins, SearchRangeBuilder.Gte(10)), searchOptions)
    33 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    34 .Exclude(movie => movie.Id)
    35 .Include(movie => movie.Title)
    36 .Include(movie => movie.Awards.Wins))
    37 .Limit(5)
    38 .ToList();
    39
    40 // print results
    41 foreach (var movie in results)
    42 {
    43 Console.WriteLine(movie.ToJson());
    44 }
    45 }
    46}
    47
    48[BsonIgnoreExtraElements]
    49public class MovieDocument
    50{
    51 [BsonIgnoreIfDefault]
    52 public ObjectId Id { get; set; }
    53 public string Title { get; set; }
    54 public Award Awards { get; set; }
    55}
    56
    57public class Award
    58{
    59 [BsonIgnoreIfDefault]
    60 public int Wins { get; set; }
    61}
  2. <connection-string>を指定します。

2
dotnet run Program.cs
{ "title" : "12 Years a Slave", "awards" : { "wins" : 267 } }
{ "title" : "Gravity", "awards" : { "wins" : 231 } }
{ "title" : "Gravity", "awards" : { "wins" : 231 } }
{ "title" : "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards" : { "wins" : 210 } }
{ "title" : "Boyhood", "awards" : { "wins" : 185 } }
1
  1. sort-by-numbers.go という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6
    7 "go.mongodb.org/mongo-driver/v2/bson"
    8 "go.mongodb.org/mongo-driver/v2/mongo"
    9 "go.mongodb.org/mongo-driver/v2/mongo/options"
    10)
    11
    12func main() {
    13 // connect to your Atlas cluster
    14 client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
    15 if err != nil {
    16 panic(err)
    17 }
    18 defer client.Disconnect(context.TODO())
    19
    20 // set namespace
    21 collection := client.Database("sample_mflix").Collection("movies")
    22
    23 // define pipeline stages
    24 searchStage := bson.D{{Key: "$search", Value: bson.D{
    25 {Key: "index", Value: "default"},
    26 {Key: "range", Value: bson.D{
    27 {Key: "path", Value: "awards.wins"},
    28 {Key: "gte", Value: 10},
    29 }},
    30 {Key: "sort", Value: bson.D{{Key: "awards.wins", Value: -1}}},
    31 }}}
    32 limitStage := bson.D{{Key: "$limit", Value: 5}}
    33 projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "awards.wins", Value: 1}, {Key: "_id", Value: 0}}}}
    34
    35 // run pipeline
    36 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
    37 if err != nil {
    38 panic(err)
    39 }
    40
    41 // print results
    42 var results []bson.D
    43 if err = cursor.All(context.TODO(), &results); err != nil {
    44 panic(err)
    45 }
    46 for _, result := range results {
    47 fmt.Println(result)
    48 }
    49}
  2. <connection-string>を指定します。

2
go run sort-by-numbers.go
[{title 12 Years a Slave} {awards [{wins 267}]}]
[{title Gravity} {awards [{wins 231}]}]
[{title Gravity} {awards [{wins 231}]}]
[{title Birdman: Or (The Unexpected Virtue of Ignorance)} {awards [{wins 210}]}]
[{title Boyhood} {awards [{wins 185}]}]
1
  1. SortByNumbers.java という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1import java.util.Arrays;
    2
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import com.mongodb.client.MongoClient;
    9import com.mongodb.client.MongoClients;
    10import com.mongodb.client.MongoCollection;
    11import com.mongodb.client.MongoDatabase;
    12import org.bson.Document;
    13
    14public class SortByNumbers {
    15 public static void main( String[] args ) {
    16 // define query
    17 Document agg =
    18 new Document("$search",
    19 new Document("index", "default")
    20 .append("range",
    21 new Document("path", "awards.wins")
    22 .append("gte", 10L))
    23 .append("sort",
    24 new Document("awards.wins", -1L)));
    25
    26 // specify connection
    27 String uri = "<connection-string>";
    28
    29 // establish connection and set namespace
    30 try (MongoClient mongoClient = MongoClients.create(uri)) {
    31 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    32 MongoCollection<Document> collection = database.getCollection("movies");
    33
    34 // run query and print results
    35 collection.aggregate(Arrays.asList(agg,
    36 limit(5),
    37 project(fields(excludeId(), include("title"), include("awards.wins")))))
    38 .forEach(doc -> System.out.println(doc.toJson()));
    39 }
    40 }
    41}

    注意

    Maven 環境でサンプル コードを実行するには、 ファイルのインポート ステートメントの上に次のコードを追加します。

    package com.mongodb.drivers;
  2. <connection-string>を指定します。

2
javac SortByNumbers.java
java SortByNumbers
{"title": "12 Years a Slave", "awards": {"wins": 267}}
{"title": "Gravity", "awards": {"wins": 231}}
{"title": "Gravity", "awards": {"wins": 231}}
{"title": "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards": {"wins": 210}}
{"title": "Boyhood", "awards": {"wins": 185}}
1
  1. SortByNumbers.kt という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun main() {
    9 // establish connection and set namespace
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12 val database = mongoClient.getDatabase("sample_mflix")
    13 val collection = database.getCollection<Document>("movies")
    14
    15 runBlocking {
    16 // define query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "default")
    20 .append(
    21 "range",
    22 Document("path", "awards.wins")
    23 .append("gte", 10L)
    24 )
    25 .append(
    26 "sort",
    27 Document("awards.wins", -1L)
    28 )
    29 )
    30
    31 // run query and print results
    32 val resultsFlow = collection.aggregate<Document>(
    33 listOf(
    34 agg,
    35 limit(5),
    36 project(fields(
    37 excludeId(),
    38 include("title", "awards.wins")
    39 ))
    40 )
    41 )
    42 resultsFlow.collect { println(it) }
    43 }
    44 mongoClient.close()
    45}
  2. <connection-string>を指定します。

2
kotlin SortByNumbers.kt
Document{{title=12 Years a Slave, awards=Document{{wins=267}}}}
Document{{title=Gravity, awards=Document{{wins=231}}}}
Document{{title=Gravity, awards=Document{{wins=231}}}}
Document{{title=Birdman: Or (The Unexpected Virtue of Ignorance), awards=Document{{wins=210}}}}
Document{{title=Boyhood, awards=Document{{wins=185}}}}
1
  1. sort-by-numbers.js という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1const { MongoClient } = require("mongodb");
    2
    3// Replace the uri string with your MongoDB deployments connection string.
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11 await client.connect();
    12
    13 // set namespace
    14 const database = client.db("sample_mflix");
    15 const coll = database.collection("movies");
    16
    17 // define pipeline
    18 const agg = [
    19 {
    20 '$search': {
    21 'index': 'default',
    22 'range': {
    23 'path': 'awards.wins',
    24 'gte': 10
    25 },
    26 'sort': {
    27 'awards.wins': -1
    28 }
    29 }
    30 }, {
    31 '$limit': 5
    32 }, {
    33 '$project': {
    34 '_id': 0,
    35 'title': 1,
    36 'awards.wins': 1
    37 }
    38 }
    39 ];
    40
    41 // run pipeline
    42 const result = await coll.aggregate(agg);
    43
    44 // print results
    45 await result.forEach((doc) => console.log(doc));
    46
    47 } finally {
    48 await client.close();
    49 }
    50}
    51run().catch(console.dir);
  2. <connection-string>を指定します。

2
node sort-by-numbers.js
{ title: '12 Years a Slave', awards: { wins: 267 } }
{ title: 'Gravity', awards: { wins: 231 } }
{ title: 'Gravity', awards: { wins: 231 } }
{
title: 'Birdman: Or (The Unexpected Virtue of Ignorance)',
awards: { wins: 210 }
}
{ title: 'Boyhood', awards: { wins: 185 } }
1
  1. sort-by-numbers.py という名前の新しいファイルを作成し、次のコードを貼り付けます。

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    8 {
    9 '$search': {
    10 'index': 'default',
    11 'range': {
    12 'path': 'awards.wins',
    13 'gte': 10
    14 },
    15 'sort': {
    16 'awards.wins': -1
    17 }
    18 }
    19 }, {
    20 '$limit': 5
    21 }, {
    22 '$project': {'_id': 0, 'title': 1, 'awards.wins': 1
    23 }
    24 }
    25]
    26
    27# run pipeline
    28result = client['sample_mflix']['movies'].aggregate(pipeline)
    29
    30# print results
    31for i in result:
    32 print(i)
  2. <connection-string>を指定します。

2
python sort-by-numbers.py
{'title': '12 Years a Slave', 'awards': {'wins': 267}}
{'title': 'Gravity', 'awards': {'wins': 231}}
{'title': 'Gravity', 'awards': {'wins': 231}}
{'title': 'Birdman: Or (The Unexpected Virtue of Ignorance)', 'awards': {'wins': 210}}
{'title': 'Boyhood', 'awards': {'wins': 185}}

sample_mflix.movies名前空間に対する次のクエリでは、 $searchステージを使用して次の処理が行われます。

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

  • sortオプションを使用して、結果を昇順で並べ替えます。

クエリは$limitステージを使用して出力を5ドキュメントに制限します。 また、 $projectステージを使用して次の操作を実行します。

  • 結果の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ステージを使用して、出力を5の結果に制限します。

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

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

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

[
{
$search: {
"compound": {
"should": [{
"wildcard": {
"query": ["Prance*"],
"path": "title",
"allowAnalyzedField": true
}
},
{
"wildcard": {
"query": ["Prince*"],
"path": "title",
"allowAnalyzedField": true
}
}]
},
"sort": {
"title": 1
}
}
}
]
SCORE: 1 _id: "573a1398f29313caabceb98e"
plot: "A farm girl nurses a wounded reindeer she believes is one of Santa's, …"
genres: Array
runtime: 103
...
title: "Prancer"
...
SCORE: 1 _id: "573a13a5f29313caabd14f54"
plot: "Preteen brothers from a broken marriage live with their mother, Denise…"
genres: Array
runtime: 91
...
title: "Prancer Returns"
...
SCORE: 1 _id: "573a13f5f29313caabde3755"
plot: "A troubled teenager attempts to conquer the love of his life by becomi…"
genres: Array
runtime: 78
...
title: "Prince"
...
SCORE: 1 _id: "573a13d8f29313caabda665f"
fullplot: "Two highway road workers spend the summer of 1988 away from their city…"
imdb: Object
year: 2013
...
title: "Prince Avalanche"
...
SCORE: 1 _id: "573a13bdf29313caabd5898a"
plot: "A New York street drama about the lives of immigrants in America seeki…"
genres: Array
runtime: 70
...
title: "Prince of Broadway"
...
SCORE: 1 _id: "573a1398f29313caabcea967"
fullplot: "A sinister secret has been kept in the basement of an abandoned Los An…"
imdb: Object
year: 1987
...
title: "Prince of Darkness"
...
SCORE: 1 _id: "573a1393f29313caabcde40d"
plot: "An unscrupulous agent for the Borgias suffers a change of heart when a…"
genres: Array
runtime: 107
...
title: "Princess of Foxes"
...
SCORE: 1 _id: "573a13b5f29313caabd43816"
plot: "A young fugitive prince and princess must stop a villain who unknowing…"
genres: Array
runtime: 116
...
title: "Prince of Persia: The Sands of Time"
...
SCORE: 1 _id: "573a1397f29313caabce8081"
plot: "A New York City narcotics detective reluctantly agrees to cooperate wi…"
genres: Array
runtime: 167
...
title: "Prince of the City"
...
SCORE: 1 _id: "573a13a2f29313caabd0a767"
plot: "Six old-style funny silhouetted fairy tales for not so-old-style peopl…"
genres: Array
runtime: 70
...
title: "Princes and Princesses"
...

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

Search Tester では、返されるドキュメント内のすべてのフィールドが表示されない場合があります。クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。

1db.movies.aggregate([{
2 $search: {
3 "index": "default",
4 "compound": {
5 "should": [{
6 "wildcard": {
7 "query": ["Prance*"],
8 "path": "title",
9 "allowAnalyzedField": true
10 }
11 },
12 {
13 "wildcard": {
14 "query": ["Prince*"],
15 "path": "title",
16 "allowAnalyzedField": true
17 }
18 }]
19 },
20 "sort": {
21 "title": 1
22 }
23 }},
24 {
25 $limit: 5
26 },
27 {
28 $project: {
29 "_id": 0,
30 "title": 1,
31 "score": { "$meta": "searchScore" }
32 }
33 }
34])
[
{ title: 'Prancer', score: 1 },
{ title: 'Prancer Returns', score: 1 },
{ title: 'Prince', score: 1 },
{ title: 'Prince Avalanche', score: 1 },
{ title: 'Prince of Broadway', score: 1 }
]

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

パイプラインステージ
クエリ

$search

{
compound: {
should: [{
wildcard: {
query: "Prance*",
path: 'title',
allowAnalyzedField: true
}},
{
wildcard: {
query: "Prince*",
path: 'title',
allowAnalyzedField: true
}
}]
},
sort: {
title: 1
}
}

$limit

5

$project

{
_id: 0,
title: 1,
score: { $meta: "searchScore" }
}

Auto Previewを有効にした場合、MongoDB Compass は$projectパイプライン ステージの横に次のドキュメントを表示します。

{
title: 'Prancer',
score: 1
},
{
title: 'Prancer Returns',
score: 1
},
{
title: 'Prince',
score: 1
},
{
title: 'Prince Avalanche',
score: 1
},
{
title: 'Prince of Boradway',
score: 1
}

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

このコード例では、次のタスクを実行します。

  • mongodb パッケージと依存関係をインポートします。

  • Atlas クラスターへの接続を確立します。

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

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

    • $limitステージを使用して、出力を5の結果に制限します。

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

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

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

  • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class SortByStrings
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our MovieDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
21
22 // define search options
23 var searchOptions = new SearchOptions<MovieDocument>()
24 {
25 Sort = Builders<MovieDocument>.Sort.Ascending(movie => movie.Title),
26 IndexName = "default"
27 };
28
29 // define and run pipeline
30 var results = moviesCollection.Aggregate()
31 .Search(Builders<MovieDocument>.Search.Compound()
32 .Should(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Prance*", true ))
33 .Should(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Prince*" )), searchOptions)
34 .Project<MovieDocument>(Builders<MovieDocument>.Projection
35 .Include(movie => movie.Title)
36 .Exclude(movie => movie.Id)
37 .MetaSearchScore(movie => movie.Score))
38 .Limit(5)
39 .ToList();
40
41 // print results
42 foreach (var movie in results)
43 {
44 Console.WriteLine(movie.ToJson());
45 }
46 }
47}
48
49[BsonIgnoreExtraElements]
50public class MovieDocument
51{
52 [BsonIgnoreIfDefault]
53 public ObjectId Id { get; set; }
54 public string Title { get; set; }
55 public double Score { get; set; }
56}
{ "title" : "Prancer", "score" : 1.0 }
{ "title" : "Prancer Returns", "score" : 1.0 }
{ "title" : "Prince", "score" : 1.0 }
{ "title" : "Prince Avalanche", "score" : 1.0 }
{ "title" : "Prince of Broadway", "score" : 1.0 }

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

このコード例では、次のタスクを実行します。

  • mongodb パッケージと依存関係をインポートします。

  • Atlas クラスターへの接続を確立します。

  • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/v2/bson"
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("sample_mflix").Collection("movies")
22
23 // define pipeline stages
24 searchStage := bson.D{{Key: "$search", Value: bson.M{
25 "index": "default",
26 "compound": bson.M{
27 "should": bson.A{
28 bson.M{
29 "wildcard": bson.D{
30 {Key: "path", Value: "title"},
31 {Key: "query", Value: "Prance*"},
32 {Key: "allowAnalyzedField", Value: true},
33 }},
34 bson.M{
35 "wildcard": bson.D{
36 {Key: "path", Value: "title"},
37 {Key: "query", Value: "Prince*"},
38 {Key: "allowAnalyzedField", Value: true},
39 }},
40 },
41 },
42 "sort": bson.D{{Key: "title", Value: 1}},
43 }}}
44
45 limitStage := bson.D{{Key: "$limit", Value: 5}}
46 projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "title", Value: 1}, {Key: "_id", Value: 0}, {Key: "score", Value: bson.D{{Key: "$meta", Value: "searchScore"}}}}}}
47
48 // run pipeline
49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
50 if err != nil {
51 panic(err)
52 }
53
54 // print results
55 var results []bson.D
56 if err = cursor.All(context.TODO(), &results); err != nil {
57 panic(err)
58 }
59 for _, result := range results {
60 fmt.Println(result)
61 }
62}
[{title Prancer} {score 1}]
[{title Prancer Returns} {score 1}]
[{title Prince} {score 1}]
[{title Prince Avalanche} {score 1}]
[{title Prince of Broadway} {score 1}]

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

このコード例では、次のタスクを実行します。

  • mongodb パッケージと依存関係をインポートします。

  • Atlas クラスターへの接続を確立します。

  • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

1import java.util.Arrays;
2import java.util.List;
3
4import static com.mongodb.client.model.Aggregates.limit;
5import static com.mongodb.client.model.Aggregates.project;
6import static com.mongodb.client.model.Projections.*;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13import java.util.Date;
14
15public class SortByString {
16 public static void main( String[] args ) {
17 // define clause
18 List<Document> shouldClause =
19 List.of(
20 new Document(
21 "wildcard",
22 new Document("query", "Prance*")
23 .append("path", "title")
24 .append("allowAnalyzedField", true)),
25 new Document(
26 "wildcard",
27 new Document("query", "Prince*")
28 .append("path", "title")
29 .append("allowAnalyzedField", true)));
30
31 // define query
32 Document agg =
33 new Document(
34 "$search",
35 new Document("index", "default")
36 .append("compound",
37 new Document("should", shouldClause))
38 .append("sort", new Document("title", 1L)));
39
40 // specify connection
41 String uri = "<connection-string>";
42
43 // establish connection and set namespace
44 try (MongoClient mongoClient = MongoClients.create(uri)) {
45 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
46 MongoCollection<Document> collection = database.getCollection("movies");
47
48 // run query and print results
49 collection.aggregate(Arrays.asList(agg,
50 limit(5),
51 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore"))))))
52 .forEach(doc -> System.out.println(doc.toJson()));
53 }
54 }
55}
{"title": "Prancer", "score": 1.0}
{"title": "Prancer Returns", "score": 1.0}
{"title": "Prince", "score": 1.0}
{"title": "Prince Avalanche", "score": 1.0}
{"title": "Prince of Broadway", "score": 1.0}

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

このコード例では、次のタスクを実行します。

  • mongodb パッケージと依存関係をインポートします。

  • Atlas クラスターへの接続を確立します。

  • クエリに一致するドキュメントをAggregateFlowインスタンスから出力します。

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_mflix")
13 val collection = database.getCollection<Document>("movies")
14
15 runBlocking {
16 // define clause
17 val shouldClause = listOf(
18 Document("wildcard", Document("query", "Prance*")
19 .append("path", "title")
20 .append("allowAnalyzedField", true)),
21 Document("wildcard", Document("query", "Prince*")
22 .append("path", "title")
23 .append("allowAnalyzedField", true))
24 )
25
26 // define query
27 val agg = Document(
28 "\$search",
29 Document("index", "default")
30 .append(
31 "compound",
32 Document("should", shouldClause)
33 )
34 .append("sort", Document("title", 1L))
35 )
36
37 // run query and print results
38 val resultsFlow = collection.aggregate<Document>(
39 listOf(
40 agg,
41 limit(5),
42 project(fields(
43 excludeId(),
44 include("title"),
45 computed("score", Document("\$meta", "searchScore"))
46 ))
47 )
48 )
49 resultsFlow.collect { println(it) }
50 }
51 mongoClient.close()
52}
Document{{title=Prancer, score=1.0}}
Document{{title=Prancer Returns, score=1.0}}
Document{{title=Prince, score=1.0}}
Document{{title=Prince Avalanche, score=1.0}}
Document{{title=Prince of Broadway, score=1.0}}

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

このコード例では、次のタスクを実行します。

  • MongoDB の Node.js ドライバーであるmongodbをインポートします。

  • Atlas クラスターへの接続を確立するためのMongoClientクラスのインスタンスを作成します。

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

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

    • $limitステージを使用して、出力を5の結果に制限します。

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

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

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

  • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployments connection string.
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
13 // set namespace
14 const database = client.db("sample_mflix");
15 const coll = database.collection("movies");
16
17 // define pipeline
18 const agg = [
19 {
20 '$search': {
21 'compound': {
22 'should': [
23 {
24 'wildcard': {
25 'query': [
26 'Prance*'
27 ],
28 'path': 'title',
29 'allowAnalyzedField': true
30 }
31 }, {
32 'wildcard': {
33 'query': [
34 'Prince*'
35 ],
36 'path': 'title',
37 'allowAnalyzedField': true
38 }
39 }
40 ]
41 },
42 'sort': { 'title': 1 }
43 }
44 }, {
45 '$limit': 5
46 }, {
47 '$project': {'_id': 0, 'title': 1, 'score': {'$meta': 'searchScore'}
48 }
49 }
50 ];
51
52 // run pipeline
53 const result = await coll.aggregate(agg);
54
55 // print results
56 await result.forEach((doc) => console.log(doc));
57
58 } finally {
59 await client.close();
60 }
61}
62run().catch(console.dir);
{ title: 'Prancer', score: 1 }
{ title: 'Prancer Returns', score: 1 }
{ title: 'Prince', score: 1 }
{ title: 'Prince Avalanche', score: 1 }
{ title: 'Prince of Broadway', score: 1 }

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

次のコード例では、次を行います。

  • pymongo、MongoDB の Python ドライバー、およびDNSシード リスト接続文字列を使用してpymongoAtlas に接続するために必要なdns モジュールをインポートします。

  • Atlas クラスターへの接続を確立するためのMongoClientクラスのインスタンスを作成します。

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

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

    • $limitステージを使用して、出力を5の結果に制限します。

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

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

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

  • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient('<connection-string>')
5
6# define pipeline
7pipeline = [
8 {'$search': {
9 'compound': {
10 'should': [{'wildcard': {'query': 'Prance*', 'path': 'title', 'allowAnalyzedField': True}},
11 {'wildcard': {'query': 'Prince*', 'path': 'title', 'allowAnalyzedField': True}}]
12 },
13 'sort': { 'title': 1 }}},
14 {'$limit': 5},
15 {'$project': {'_id': 0, 'title': 1, 'score': {'$meta': 'searchScore'}}}
16]
17
18# run pipeline
19result = client['sample_mflix']['movies'].aggregate(pipeline)
20
21# print results
22for i in result:
23 print(i)
{'title': 'Prancer', 'score': 1.0}
{'title': 'Prancer Returns', 'score': 1.0}
{'title': 'Prince', 'score': 1.0}
{'title': 'Prince Avalanche', 'score': 1.0}
{'title': 'Prince of Broadway', 'score': 1.0}

Atlas Search 結果には、 PrancePrinceで始まる映画タイトルが含まれているドキュメントが含まれています。 Atlas Search Atlas Search title フィールドで昇順にドキュメントをソートするため、Prance の後に Prince が続くタイトルを返します。

次のクエリは、大文字と小文字に関係なく結果をソートする方法を示しています。 テキスト演算子を使用して、 titleフィールドにtrainというタームが含まれる映画を検索し、その結果をtitleフィールド値で昇順にソートします。

クエリでは、結果内のドキュメントを5に制限するための$limitステージと、次の操作を行うための$projectステージを指定します。

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

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

[
{
"$search": {
"text": {
"path": "title",
"query": "train",
},
"sort": {
"title": 1
}
}
}
]
SCORE: 3.317898988723755 _id: "573a139cf29313caabcf662c"
plot: "A train filled with atomic devices threatens to destroy the city of De…"
genres: Array
runtime: 122
SCORE: 3.317898988723755 _id: "64de50ae2932de4dd3203061"
genres: Array
title: "atomic train"
awards: Object
SCORE: 2.228306293487549 _id: "573a13bbf29313caabd52ff4"
fullplot: "Long ago up North on the Island of Berk, the young Viking, Hiccup, wan…"
imdb: Object
year: 2010
SCORE: 2.228306293487549 _id: "64de50da2932de4dd3204393"
genres: Array
title: "how to train your dragon"
awards: Object
SCORE: 2.008449077606201 _id: "573a13ccf29313caabd83281"
plot: "When Hiccup and Toothless discover an ice cave that is home to hundred…"
genres: Array
runtime: 102
SCORE: 1.4400973320007324 _id: "573a13b1f29313caabd36490"
plot: "The life and times of Howard Zinn: the historian, activist, and author…"
genres: Array
runtime: 78
SCORE: 2.228306293487549 _id: "573a1394f29313caabce0fb4"
plot: "A marshal tries to bring the son of an old friend, an autocratic cattl…"
genres: Array
runtime: 95
SCORE: 2.8528976440429688 _id: "573a13c8f29313caabd78a6b"
plot: "A couple embarks on a journey home for Chinese new year along with 130…"
genres: Array
runtime: 85
SCORE: 2.502213716506958 _id: "573a13baf29313caabd50811"
plot: "Two thugs from the Perth suburb of Midland catch the last train to Fre…"
genres: Array
runtime: 89
SCORE: 2.502213716506958 _id: "573a13a7f29313caabd1b667"
fullplot: "A teacher and a gangster meet by chance in a small town pharmacy. As a…"
imdb: Object
year: 2002

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

SCORE: 3.317898988723755 _id: "573a139cf29313caabcf662c"
plot: "A train filled with atomic devices threatens to destroy the city of De…"
genres: Array
runtime: 122
SCORE: 2.2382168769836426 _id: "573a13bbf29313caabd52ff4"
fullplot: "Long ago up North on the Island of Berk, the young Viking, Hiccup, wan…"
imdb: object
year: 2010
SCORE: 2.008449077606201 _id: "573a13ccf29313caabd83281"
plot: "When Hiccup and Toothless discover an ice cave that is home to hundred…"
genres: Array
runtime: 102
SCORE: 1.4400973320007324 _id: "573a13b1f29313caabd36490"
plot: "The life and times of Howard Zinn: the historian, activist, and author…"
genres: Array
runtime: 78
SCORE: 2.8528976440429688 _id: "573a13c8f29313caabd78a6b"
plot: "A couple embarks on a journey home for Chinese new year along with 130…"
genres: Array
runtime: 85
SCORE: 2.228306293487549 _id: "573a1394f29313caabce0fb4"
plot: "A marshal tries to bring the son of an old friend, an autocratic cattl…"
genres: Array
runtime: 95
SCORE: 2.502213716506958 _id: "573a13baf29313caabd50811"
plot: "Two thugs from the Perth suburb of Midland catch the last train to Fre…"
genres: Array
runtime: 89
SCORE: 2.502213716506958 _id: "573a13a7f29313caabd1b667"
fullplot: "A teacher and a gangster meet by chance in a small town pharmacy. As a…"
imdb: Object
year: 2002
SCORE: 3.3326687812805176 _id: "573a139af29313caabcef573"
plot: "A vengeful New York transit cop decides to steal a trainload of subway…"
genres: Array
runtime: 110
SCORE: 3.3326687812805176 _id: "573a1398f29313caabceb8f2"
plot: "Three stories are connected by a Memphis hotel and the spirit of Elvis…"
genres: Array
runtime: 110

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

db.movies.aggregate(
{
"$search": {
"index": "default",
"text": {
"path": "title",
"query": "train",
},
"sort": {
"title": 1
}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 1,
"title": 1,
"awards": 1,
"score": { $meta: "searchScore" }
}
}
)
[
{
_id: ObjectId("573a139cf29313caabcf662c"),
title: 'Atomic Train',
awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
score: 3.317898988723755
},
{
_id: ObjectId("64de50ae2932de4dd3203061"),
title: 'atomic train',
awards: { wins: 1, nominations: 1 },
score: 3.317898988723755
},
{
_id: ObjectId("573a13bbf29313caabd52ff4"),
title: 'How to Train Your Dragon',
awards: {
wins: 32,
nominations: 51,
text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
},
score: 2.228306293487549
},
{
_id: ObjectId("64de50da2932de4dd3204393"),
title: 'how to train your dragon',
awards: { wins: 32, nominations: 51 },
score: 2.228306293487549
},
{
_id: ObjectId("573a13ccf29313caabd83281"),
title: 'How to Train Your Dragon 2',
awards: {
wins: 18,
nominations: 52,
text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
},
score: 2.008449077606201
}
]

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

[
{
_id: ObjectId("573a139cf29313caabcf662c"),
title: 'Atomic Train',
awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
score: 3.3326687812805176
},
{
_id: ObjectId("573a13bbf29313caabd52ff4"),
title: 'How to Train Your Dragon',
awards: {
wins: 32,
nominations: 51,
text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
},
score: 2.2382168769836426
},
{
_id: ObjectId("573a13ccf29313caabd83281"),
title: 'How to Train Your Dragon 2',
awards: {
wins: 18,
nominations: 52,
text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
},
score: 2.0173802375793457
},
{
_id: ObjectId("573a13b1f29313caabd36490"),
title: "Howard Zinn: You Can't Be Neutral on a Moving Train",
awards: { wins: 1, nominations: 0, text: '1 win.' },
score: 1.446497917175293
},
{
_id: ObjectId("573a13c8f29313caabd78a6b"),
title: 'Last Train Home',
awards: { wins: 14, nominations: 9, text: '14 wins & 9 nominations.' },
score: 2.8655927181243896
}
]

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

パイプラインステージ
クエリ

$search

{
"index": "default",
"text": {
"path": "title",
"query": "train",
},
"sort": {
"title": 1,
}
}

$limit

5

$project

{
"_id": 1,
"title": 1,
"awards": 1,
"score": { $meta: "searchScore" }
}

Auto Preview有効にした場合、MongoDB Compass は$projectパイプライン ステージの横に次のドキュメントを表示します。

_id: ObjectId('573a139cf29313caabcf662c')
title: 'Atomic Train'
awards: Object
score: 3.317898988723755
_id: ObjectId("64de50ae2932de4dd3203061")
title: 'atomic train'
awards: Object
score: 3.317898988723755
_id: ObjectId('573a13bbf29313caabd52ff4')
title: 'How to Train Your Dragon'
awards: Object
score: 2.228306293487549
_id: ObjectId("64de50da2932de4dd3204393"),
title: 'how to train your dragon'
awards:
score: 2.228306293487549
_id: ObjectId('573a13ccf29313caabd83281')
title: 'How to Train Your Dragon 2'
awards: object
score: 2.0173802375793457

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class CaseInsensitiveSort
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our MovieDocument
14 var camelCaseConvention = new ConventionPack { new camelCaseConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var yourDatabase = mongoClient.GetDatabase("sample_mflix");
20 var moviesCollection = yourDatabase.GetCollection<MovieDocument>("movies");
21
22 // define options for search
23 var searchOptions = new SearchOptions<MovieDocument>() {
24 Sort = Builders<MovieDocument>.Sort.Ascending(movie => movie.Title),
25 IndexName = "default"
26 };
27
28 // define and run pipeline
29 var results = moviesCollection.Aggregate()
30 .Search(Builders<MovieDocument>.Search.Text(movie => movie.Title, "train"), searchOptions)
31 .Limit (5)
32 .Project<MovieDocument>(Builders<MovieDocument>.Projection
33 .Include(movie => movie.Id)
34 .Include(movie => movie.Title)
35 .Include(movie => movie.Awards)
36 .MetaSearchScore(movie => movie.Score))
37 .ToList();
38
39 // print results
40 foreach (var movie in results)
41 {
42 Console.WriteLine(movie.ToJson());
43 }
44 }
45}
46
47[BsonIgnoreExtraElements]
48public class MovieDocument
49{
50 [BsonIgnoreIfDefault]
51 public ObjectId Id { get; set; }
52 public string Title { get; set; }
53 public Award Awards { get; set; }
54 public double Score { get; set; }
55}
56
57[BsonIgnoreExtraElements]
58public class Award
59{
60 public int Wins { get; set; }
61 public int Nominations { get; set; }
62}
{ "_id" : ObjectId("573a139cf29313caabcf662c"), "title" : "Atomic Train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035578727722168 }
{ "_id" : ObjectId("64de50ae2932de4dd3203061"), "title" : "atomic train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035578727722168 }
{ "_id" : ObjectId("573a13bbf29313caabd52ff4"), "title" : "How to Train Your Dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186923027038574 }
{ "_id" : ObjectId("64de50da2932de4dd3204393"), "title" : "how to train your dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186923027038574 }
{ "_id" : ObjectId("573a13ccf29313caabd83281"), "title" : "How to Train Your Dragon 2", "awards" : { "wins" : 18, "nominations" : 52 }, "score" : 1.9997868537902832 }

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

{ "_id" : ObjectId("573a139cf29313caabcf662c"), "title" : "Atomic Train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035225868225098 }
{ "_id" : ObjectId("573a13bbf29313caabd52ff4"), "title" : "How to Train Your Dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186522483825684 }
{ "_id" : ObjectId("573a13ccf29313caabd83281"), "title" : "How to Train Your Dragon 2", "awards" : { "wins" : 18, "nominations" : 52 }, "score" : 1.9997482299804688 }
{ "_id" : ObjectId("573a13b1f29313caabd36490"), "title" : "Howard Zinn: You Can't Be Neutral on a Moving Train", "awards" : { "wins" : 1, "nominations" : 0 }, "score" : 1.4338588714599609 }
{ "_id" : ObjectId("573a13c8f29313caabd78a6b"), "title" : "Last Train Home", "awards" : { "wins" : 14, "nominations" : 9 }, "score" : 2.8405368328094482 }

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("sample_mflix").Collection("movies")
22
23 // define pipeline stages
24 searchStage := bson.D{{"$search", bson.M{
25 "index": "default",
26 "text": bson.D{
27 {"path", "title"},
28 {"query", "train"},
29 },
30 "sort": bson.D{{"title", 1}},
31 }}}
32 limitStage := bson.D{{"$limit", 5}}
33 projectStage := bson.D{{"$project", bson.D{{"_id", 1}, {"title", 1}, {"awards", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
34
35 // run pipeline
36 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
37 if err != nil {
38 panic(err)
39 }
40
41 // print results
42 var results []bson.D
43 if err = cursor.All(context.TODO(), &results); err != nil {
44 panic(err)
45 }
46 for _, result := range results {
47 fmt.Println(result)
48 }
49}
[{_id ObjectID("573a139cf29313caabcf662c")} {title Atomic Train} {awards [{wins 1} {nominations 1} {text 1 win & 1 nomination.}]} {score 3.317898988723755}]
[{_id ObjectId("64de50ae2932de4dd3203061")} {title atomic train} {awards [{wins 1} {nominations 1}]} {score 3.317898988723755}]
[{_id ObjectID("573a13bbf29313caabd52ff4")} {title How to Train Your Dragon} {awards [{wins 32} {nominations 51} {text Nominated for 2 Oscars. Another 30 wins & 51 nominations.}]} {score 2.228306293487549}]
[{_id ObjectId("64de50da2932de4dd3204393")} {title how to train your dragon} {awards [{wins 32} {nominations 51}]} {score 2.228306293487549}]
[{_id ObjectID("573a13ccf29313caabd83281")} {title How to Train Your Dragon 2} {awards [{wins 18} {nominations 52} {text Nominated for 1 Oscar. Another 17 wins & 52 nominations.}]} {score 2.008449077606201}]

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

[{_id ObjectID("573a139cf29313caabcf662c")} {title Atomic Train} {awards [{wins 1} {nominations 1} {text 1 win & 1 nomination.}]} {score 3.3326687812805176}]
[{_id ObjectID("573a13bbf29313caabd52ff4")} {title How to Train Your Dragon} {awards [{wins 32} {nominations 51} {text Nominated for 2 Oscars. Another 30 wins & 51 nominations.}]} {score 2.2382168769836426}]
[{_id ObjectID("573a13ccf29313caabd83281")} {title How to Train Your Dragon 2} {awards [{wins 18} {nominations 52} {text Nominated for 1 Oscar. Another 17 wins & 52 nominations.}]} {score 2.0173802375793457}]
[{_id ObjectID("573a13b1f29313caabd36490")} {title Howard Zinn: You Can't Be Neutral on a Moving Train} {awards [{wins 1} {nominations 0} {text 1 win.}]} {score 1.446497917175293}]
[{_id ObjectID("573a13c8f29313caabd78a6b")} {title Last Train Home} {awards [{wins 14} {nominations 9} {text 14 wins & 9 nominations.}]} {score 2.8655927181243896}]

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.*;
5import com.mongodb.client.MongoClient;
6import com.mongodb.client.MongoClients;
7import com.mongodb.client.MongoCollection;
8import com.mongodb.client.MongoDatabase;
9import org.bson.Document;
10
11public class CaseInsensitiveQuery {
12 public static void main( String[] args ) {
13 // define query
14 Document agg =
15 new Document("$search",
16 new Document("index", "default")
17 .append("text",
18 new Document("path", "title")
19 .append("query", "train"))
20 .append("sort",
21 new Document("title", 1)));
22
23 // specify connection
24 String uri = "<connection-string>";
25
26 // establish connection and set namespace
27 try (MongoClient mongoClient = MongoClients.create(uri)) {
28 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
29 MongoCollection<Document> collection = database.getCollection("movies");
30
31 // run query and print results
32 collection.aggregate(Arrays.asList(agg,
33 limit(5),
34 project(fields(include("_id"), include("title"), include("awards"), computed("score", new Document("$meta", "searchScore"))))))
35 .forEach(doc -> System.out.println(doc.toJson()));
36 }
37 }
38}
{"_id": {"$oid": "573a139cf29313caabcf662c"}, "title": "Atomic Train", "awards": {"wins": 1, "nominations": 1, "text": "1 win & 1 nomination."}, "score": 3.317898988723755}
{"_id": {"$oid": "64de50ae2932de4dd3203061"}, "title": "atomic train", "awards": {"wins": 1, "nominations": 1}, "score": 3.317898988723755}
{"_id": {"$oid": "573a13bbf29313caabd52ff4"}, "title": "How to Train Your Dragon", "awards": {"wins": 32, "nominations": 51, "text": "Nominated for 2 Oscars. Another 30 wins & 51 nominations."}, "score": 2.228306293487549}
{"_id": {"$oid": "64de50da2932de4dd3204393"}, "title": "how to train your dragon", "awards": {"wins": 32, "nominations": 51}, "score": 2.228306293487549}
{"_id": {"$oid": "573a13ccf29313caabd83281"}, "title": "How to Train Your Dragon 2", "awards": {"wins": 18, "nominations": 52, "text": "Nominated for 1 Oscar. Another 17 wins & 52 nominations."}, "score": 2.008449077606201}

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

{"_id": {"$oid": "573a139cf29313caabcf662c"}, "title": "Atomic Train", "awards": {"wins": 1, "nominations": 1, "text": "1 win & 1 nomination."}, "score": 3.3326687812805176}
{"_id": {"$oid": "573a13bbf29313caabd52ff4"}, "title": "How to Train Your Dragon", "awards": {"wins": 32, "nominations": 51, "text": "Nominated for 2 Oscars. Another 30 wins & 51 nominations."}, "score": 2.2382168769836426}
{"_id": {"$oid": "573a13ccf29313caabd83281"}, "title": "How to Train Your Dragon 2", "awards": {"wins": 18, "nominations": 52, "text": "Nominated for 1 Oscar. Another 17 wins & 52 nominations."}, "score": 2.0173802375793457}
{"_id": {"$oid": "573a13b1f29313caabd36490"}, "title": "Howard Zinn: You Can't Be Neutral on a Moving Train", "awards": {"wins": 1, "nominations": 0, "text": "1 win."}, "score": 1.446497917175293}
{"_id": {"$oid": "573a13c8f29313caabd78a6b"}, "title": "Last Train Home", "awards": {"wins": 14, "nominations": 9, "text": "14 wins & 9 nominations."}, "score": 2.8655927181243896}

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_mflix")
13 val collection = database.getCollection<Document>("movies")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "default")
20 .append(
21 "text",
22 Document("path", "title")
23 .append("query", "train")
24 )
25 .append(
26 "sort",
27 Document("title", 1)
28 )
29 )
30
31 // run query and print results
32 val resultsFlow = collection.aggregate<Document>(
33 listOf(
34 agg,
35 limit(5),
36 project(fields(
37 excludeId(),
38 include("title", "awards"),
39 computed("score", Document("\$meta", "searchScore"))
40 ))
41 )
42 )
43 resultsFlow.collect { println(it) }
44 }
45 mongoClient.close()
46}
Document{{title=atomic train, awards=Document{{wins=1, nominations=1}}, score=3.3326687812805176}}
Document{{title=Atomic Train, awards=Document{{wins=1, nominations=1, text=1 win & 1 nomination.}}, score=3.3326687812805176}}
Document{{title=how to train your dragon, awards=Document{{wins=32, nominations=51}}, score=2.2382168769836426}}
Document{{title=How to Train Your Dragon, awards=Document{{wins=32, nominations=51, text=Nominated for 2 Oscars. Another 30 wins & 51 nominations.}}, score=2.2382168769836426}}
Document{{title=How to Train Your Dragon 2, awards=Document{{wins=18, nominations=52, text=Nominated for 1 Oscar. Another 17 wins & 52 nominations.}}, score=2.0173802375793457}}

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

Document{{title=Atomic Train, awards=Document{{wins=1, nominations=1, text=1 win & 1 nomination.}}, score=3.3326687812805176}}
Document{{title=How to Train Your Dragon, awards=Document{{wins=32, nominations=51, text=Nominated for 2 Oscars. Another 30 wins & 51 nominations.}}, score=2.2382168769836426}}
Document{{title=How to Train Your Dragon 2, awards=Document{{wins=18, nominations=52, text=Nominated for 1 Oscar. Another 17 wins & 52 nominations.}}, score=2.0173802375793457}}
Document{{title=Howard Zinn: You Can't Be Neutral on a Moving Train, awards=Document{{wins=1, nominations=0, text=1 win.}}, score=1.446497917175293}}
Document{{title=Last Train Home, awards=Document{{wins=14, nominations=9, text=14 wins & 9 nominations.}}, score=2.8655927181243896}}

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployments connection string.
4const uri =
5 "<connection-string>";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
13 // set namespace
14 const database = client.db("sample_mflix");
15 const coll = database.collection("movies");
16
17 // define pipeline
18 const agg = [
19 {
20 '$search': {
21 'index': 'default',
22 'text': { 'path': 'title', 'query': 'train' },
23 'sort': { 'title': 1 }
24 }
25 }, {
26 '$limit': 5
27 }, {
28 '$project': { '_id': 1, 'title': 1, 'awards': 1, 'score': { '$meta': 'searchScore' }}
29 }
30 ];
31
32 // run pipeline
33 const result = await coll.aggregate(agg);
34
35 // print results
36 await result.forEach((doc) => console.log(doc));
37
38 } finally {
39 await client.close();
40 }
41}
42run().catch(console.dir);
{
_id: new ObjectId("573a139cf29313caabcf662c"),
title: 'Atomic Train',
awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
score: 3.317898988723755
}
{
_id: new ObjectId("64de50ae2932de4dd3203061"),
title: 'atomic train',
awards: { wins: 1, nominations: 1 },
score: 3.317898988723755
}
{
_id: new ObjectId("573a13bbf29313caabd52ff4"),
title: 'How to Train Your Dragon',
awards: {
wins: 32,
nominations: 51,
text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
},
score: 2.228306293487549
}
{
_id: new ObjectId("64de50da2932de4dd3204393"),
title: 'how to train your dragon',
awards: { wins: 32, nominations: 51 },
score: 2.228306293487549
}
{
_id: new ObjectId("573a13ccf29313caabd83281"),
title: 'How to Train Your Dragon 2',
awards: {
wins: 18,
nominations: 52,
text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
},
score: 2.008449077606201
}

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

{
_id: new ObjectId("573a139cf29313caabcf662c"),
title: 'Atomic Train',
awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' },
score: 3.3326687812805176
}
{
_id: new ObjectId("573a13bbf29313caabd52ff4"),
title: 'How to Train Your Dragon',
awards: {
wins: 32,
nominations: 51,
text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'
},
score: 2.2382168769836426
}
{
_id: new ObjectId("573a13ccf29313caabd83281"),
title: 'How to Train Your Dragon 2',
awards: {
wins: 18,
nominations: 52,
text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'
},
score: 2.0173802375793457
}
{
_id: new ObjectId("573a13b1f29313caabd36490"),
title: "Howard Zinn: You Can't Be Neutral on a Moving Train",
awards: { wins: 1, nominations: 0, text: '1 win.' },
score: 1.446497917175293
}
{
_id: new ObjectId("573a13c8f29313caabd78a6b"),
title: 'Last Train Home',
awards: { wins: 14, nominations: 9, text: '14 wins & 9 nominations.' },
score: 2.8655927181243896
}

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient('<connection-string>')
5
6# define pipeline
7pipeline = [
8 {
9 '$search': {
10 'index': 'default',
11 'text': { 'path': 'title', 'query': 'train' },
12 'sort': { 'title': 1 }
13 }
14 }, {
15 '$limit': 5
16 }, {
17 '$project': { '_id': 1, 'title': 1, 'awards': 1, 'score': { '$meta': 'searchScore' } }
18 }
19]
20
21# run pipeline
22result = client['sample_mflix']['movies'].aggregate(pipeline)
23
24# print results
25for i in result:
26 print(i)
{'_id': ObjectId('573a139cf29313caabcf662c'), 'title': 'Atomic Train', 'awards': {'wins': 1, 'nominations': 1, 'text': '1 win & 1 nomination.'}, 'score': 3.317898988723755}
{'_id': ObjectId('64de50ae2932de4dd3203061'), 'title': 'atomic train', 'awards': {'wins': 1, 'nominations': 1}, 'score': 3.317898988723755}
{'_id': ObjectId('573a13bbf29313caabd52ff4'), 'title': 'How to Train Your Dragon', 'awards': {'wins': 32, 'nominations': 51, 'text': 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'}, 'score': 2.228306293487549}
{'_id': ObjectId('64de50da2932de4dd3204393'), 'title': 'how to train your dragon', 'awards': {'wins': 32, 'nominations': 51}, 'score': 2.228306293487549}
{'_id': ObjectId('573a13ccf29313caabd83281'), 'title': 'How to Train Your Dragon 2', 'awards': {'wins': 18, 'nominations': 52, 'text': 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'}, 'score': 2.008449077606201}

結果には、大文字と小文字に関係なくソートされたドキュメントが含まれます。 ただし、 normalizernoneに設定すると、Atlas Search は次の結果を返します。

{'_id': ObjectId('573a139cf29313caabcf662c'), 'title': 'Atomic Train', 'awards': {'wins': 1, 'nominations': 1, 'text': '1 win & 1 nomination.'}, 'score': 3.3326687812805176}
{'_id': ObjectId('573a13bbf29313caabd52ff4'), 'title': 'How to Train Your Dragon', 'awards': {'wins': 32, 'nominations': 51, 'text': 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'}, 'score': 2.2382168769836426}
{'_id': ObjectId('573a13ccf29313caabd83281'), 'title': 'How to Train Your Dragon 2', 'awards': {'wins': 18, 'nominations': 52, 'text': 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'}, 'score': 2.0173802375793457}
{'_id': ObjectId('573a13b1f29313caabd36490'), 'title': "Howard Zinn: You Can't Be Neutral on a Moving Train", 'awards': {'wins': 1, 'nominations': 0, 'text': '1 win.'}, 'score': 1.446497917175293}
{'_id': ObjectId('573a13c8f29313caabd78a6b'), 'title': 'Last Train Home', 'awards': {'wins': 14, 'nominations': 9, 'text': '14 wins & 9 nominations.'}, 'score': 2.8655927181243896}

大文字と小文字を正規化せずに結果を並べ替えるには、インデックス定義で normalizer オプションを none(7 行)に設定し、インデックス定義を保存して、クエリを再実行します。

次のクエリは、範囲演算子を使用して、 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 および欠損値によるソート 」を参照してください。

昇順ソート中に、Atlas 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 }
]

降順ソート中に、Atlas 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 として指定すると、Atlas 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 として指定すると、Atlas 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 として指定すると、Atlas 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 として指定すると、Atlas 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 }
]

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

フィールドc にマルチタイプの配列を含む追加のドキュメントがある場合、ユーザーコレクションに対する次のクエリを検討してみましょう。

db.users.insertOne({
"_id": 7,
"a": UUID("03e32aa9-1cbd-43b8-b9d6-18b171a03cc7"),
"b": "hello",
"c": [ false, null, 15 ]
})

bhello次のクエリは、テキスト演算子を使用してフィールド で文字列 を検索し、その結果をフィールドc でソートします。

注意

noData: lowest並べ替え構文で を設定する方法は、デフォルトのと同じです。

昇順ソートの場合、Atlas Search は、複数型の配列を表すために、最も低いBSON型の要素を使用します。デフォルトでは 、Atlas Search は null または欠落値を最小のBSON値と見なします。したがって、Atlas Search は null を使用して _id: 7 を持つドキュメントのマルチタイプ配列を表し、このドキュメントを他の 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.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 }
]

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

降順ソートの場合、Atlas Search は、複数型の配列を表すために、最も高いBSON type の要素を使用します。Atlas Searchfalse _id: 7では、配列内の最上位のBSON型であるため、 を使用して を含むドキュメントのマルチタイプ配列を表します。Atlas Search は true 値も false 値を超えるとランク付けしているため、_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 },
]

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

次のクエリでは、並べ替え中にnoData: highest null 値を最上位のBSON型として設定するには、 を指定します。

昇順ソートの場合、Atlas Search は、複数型の配列を表すために、最も低いBSON型の要素を使用します。noData: highestクエリでは、null または欠損値を最高のBSON値と見なすために が指定されます。したがって、Atlas Search15 は を使用して_id: 7 を持つドキュメントの複数型配列を表します。これは、配列内で数値が次に低いBSON型であるためです。

詳細については、「 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 }
]

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

降順ソートの場合、Atlas Search は、複数型の配列を表すために、最も高いBSON type の要素を使用します。クエリではnoData highestnull または欠落値を最高のBSON値として設定するために、 nullフィールドを として指定するため、Atlas Search_id: 7 は を使用して を持つドキュメントのマルチタイプ配列を表し、このドキュメントを で返します。は、他の null および欠落値とともに結果の先頭にあります。

詳細については、「 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 }
]

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

次のクエリは、 sample_airbnb.listingsAndReviewsコレクションでPortugalの プロパティを検索し、その結果をbooleanフィールドis_location_exactの降順で並べ替えます。

クエリは$limitステージを使用して出力を5ドキュメントに制限します。 また、 $projectステージを使用して、結果のnameproperty_typeaddress.countryaddress.location.is_location_exact以外のすべてのフィールドを省略します。

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です。降順ソートでは、Atlas Search はtrueの値をfalseの値より超えてランク付けするためです。 前のクエリの9行の値を1に変更して昇順並べ替えを行うと、Atlas 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 日以降にリリースされた映画が優先されます。

  • 結果を賞の数で降順に並べ替え、次に映画タイトルの昇順で並べ替え、次に公開日の降順で並べ替えます。

クエリは$limitステージを使用して出力を10ドキュメントに制限します。 また、 $projectステージを使用して次の操作を実行します。

  • 結果の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オプションを使用して、結果をリリース日の降順で並べ替えます。

クエリは、 $limitステージを使用して次の処理を実行します。

  • docs出力フィールドの5ドキュメントに出力を制限します。

  • meta出力フィールドの1ドキュメントへの出力を制限します。

$projectステージを使用して、 awards.winsreleasedtitleフィールドを除くすべてのフィールドを省略します。

また、 $replaceWithステージを使用して$$SEARCH_META変数に保存されているメタデータの結果をmeta出力フィールドに含め、 $setステージを使用してmetaフィールドを結果に追加します。

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というタームが含まれる映画を検索します。

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

クエリは$limitステージを使用して出力を5ドキュメントに制限します。 また、 $projectステージを使用して次のアクションを実行します。

  • 結果の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というタームが含まれる映画を検索します。

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

クエリは$limitステージを使用して出力を5ドキュメントに制限します。 また、 $projectステージを使用して次のアクションを実行します。

  • 結果の_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フィールドの値で昇順に並べ替え、同一のスコアを持つ結果を作成します。

クエリは$limitステージを使用して出力を5ドキュメントに制限します。 また、 $projectステージを使用して次のアクションを実行します。

  • 結果の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
}
]

戻る

スコアの詳細