Atlas Search 結果を並べ替える方法
このチュートリアルでは、Atlas Search の結果を、 sample_mflix.movies
コレクション内の数値フィールド、日付フィールド、string フィールドで昇順または降順でソートする方法について説明します。 また、Atlas Search の結果を大文字と小文字を区別せずに並べ替える方法も示します。 コレクションに Atlas Search インデックスを作成するときに、string フィールドの値を小文字に正規化するようにインデックスを構成できます。 これにより、ソートされたフィールドの大文字と小文字に関係なく、クエリ結果をソートできます。
Atlas Search sort
オプションのデフォルトの動作を使用して、Atlas Search の結果を数値フィールド、日付フィールド、string フィールドで並べ替える方法については、チュートリアルで次の手順に従います。
Atlas Searchstring
title
という名前のreleased
フィールド、 という名前の日付フィールド、 という名前の数値フィールドにawards.wins
sample_mflix.movies
インデックスを作成し、これらのフィールドに対してクエリを実行し、これらのフィールドで結果を並べ替えます。sample_mflix.movies
コレクション内のtitle
、released
、awards.wins
フィールドに対して Atlas Search クエリを実行し、結果をこれらのフィールドで昇順または降順でソートします。
Atlas Search sort
オプションを使用して、string フィールドの値を小文字に正規化して Atlas Search 結果を並べ替える方法を示すには、チュートリアルでは次の手順に従います。
サンプル ドキュメントを Atlas クラスターの
sample_mflix.movies
コレクションにロードします。title
という名前の string フィールドに、実行中のクエリとこのフィールドで結果を並べ替える両方用の Atlas Search インデックスを作成します。コレクションの
title
フィールドに対して Atlas Search クエリを実行し、結果をインデックス付きフィールドで並べ替えます。
開始する前に、Atlas クラスターが前提条件 に記載されている要件を満たしていることを確認してください。
Atlas Search インデックスを作成するには、プロジェクトに対するProject Data Access Admin
以上のアクセス権が必要です。
サンプル データのロード
デフォルトのsort
動作を使用して、 sample_mflix.movies
コレクション内のドキュメントを数値フィールド、日付フィールド、string フィールドで並べ替えるには、このセクションをスキップして、コレクションのインデックスの作成に進むことができます。
Overview
Atlas Search が大文字と小文字に関係なくドキュメントをソートする方法を示すために、サンプル ドキュメントを提供します。 各サンプル ドキュメントは映画を表し、映画のタイトル(小文字)、ジャンル、付与数を指定する 3 つのフィールドが含まれています。 このセクションでは、サンプル ドキュメントを Atlas クラスターのsample_mflix.movies
コレクションにロードします。 Atlas UI または mongosh
を使用してサンプル コレクションをロードできます。
手順
Atlas Atlasで、プロジェクトの {0 ページにGoします。GoClusters
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
Collections ページに移動します。
クラスターの [Browse Collections] ボタンをクリックします。
Data Explorerが表示されます。
コレクションを Atlas クラスター内のデータベースにロードします。
Atlas UI またはmongosh
からコレクションを読み込むことができます。
sample_mflix
データベースを展開し、movies
コレクションを選択します。コレクションに追加するサンプルドキュメントごとに、次の操作を行います。
デフォルトのドキュメントを置き換えるには、 Insert Documentをクリックし、 JSONビュー( {} )を選択します。
次のサンプル ドキュメントを一度に 1 つずつコピーして貼り付け、 Insertをクリックして各ドキュメントをコレクションに追加します。
1 { 2 "genres": [ "Action", "Drama", "Thriller" ], 3 "title": "atomic train", 4 "awards": { "wins": 1, "nominations": 1 } 5 } 1 { 2 "genres": [ "Animation", "Adventure", "Family" ], 3 "title": "how to train your dragon", 4 "awards": { "wins": 32, "nominations": 51 } 5 }
接続するクラスターの Connect をクリックします。
Shellを選択し、
mongosh
を介してクラスターに接続する手順を完了します。詳しくは、「
mongosh
経由で接続 」を参照してください。mongosh
のsample_mflix
データベースに切り替えます。use sample_mflix switched to db sample_mflix 選択したデータベースにコレクションを読み込みするには、
mongosh
で次のコマンドを実行します。1 db.movies.insertMany([ 2 { 3 "_id": 1, 4 "genres": [ "Action", "Drama", "Thriller" ], 5 "title": "atomic train", 6 "awards": { wins: 1, nominations: 1 } 7 }, 8 { 9 "_id": 2, 10 "genres": [ "Animation", "Adventure", "Family" ], 11 "title": "how to train your dragon", 12 "awards": { "wins": 32, "nominations": 51 }, 13 } 14 ]) { acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
Atlas Search インデックスの作成
Overview
このセクションでは、 sample_mflix.movies
コレクション内のtitle
、 released
、およびawards.wins
フィールドに Atlas Search インデックスを作成し、これらのフィールドに対してクエリを実行し、結果をこれらのフィールドで並べ替えます。
このセクションでは、 sample_mflix.movies
コレクションのtitle
フィールドに Atlas Search インデックスを作成し、このフィールドに対してクエリを実行し、結果をこのフィールドで並べ替えます。
手順
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックス構成を開始します。
ページで次の選択を行い、[]Next をクリックします。
Search Type | Atlas Searchインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定します。
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
インデックスの定義を指定します。
次のインデックス定義。
クエリと結果をフィールドで並べ替える両方で、
awards.wins
フィールドを数値型としてインデックスします。クエリと結果をフィールドで並べ替える両方で、
released
フィールドを日付型としてインデックスします。title
フィールドのインデックス作成と検索の両方に使用するキーワードアナライザを指定し、title
フィールドを次のタイプとしてインデックス化します。Atlas Search Visual Editorまたは Atlas Search JSON Editorを使用して Atlas UI でインデックスを作成できます。
[Refine Your Index] をクリックします。
Index Configurationsセクションで、Dynamic Mapping を無効に切り替える。
Field Mappingsセクションで、 Add FieldをクリックしてAdd Field Mappingウィンドウを表示します。
[Customized Configuration] をクリックします。
次のフィールドを一度に 1 つずつ、対応するドロップダウンからフィールド名とデータ型を選択し、プロパティを設定するか、デフォルトを受け入れて、 Addをクリックします。
フィールド名データ型プロパティawards.wins
番号
デフォルトを受け入れます。
released
日付
デフォルトを受け入れます。
title
Token
デフォルトを受け入れます。
title
文字列
[ Index Analyzer ] ドロップダウンと [ Search Analyzer ] ドロップダウンの両方から [
lucene.keyword
] を選択します。
デフォルトのインデックス定義を、以下の定義で置き換えます。
{ "mappings": { "dynamic": false, "fields": { "awards": { "dynamic": false, "fields": { "wins": [ { "type": "number" } ] }, "type": "document" }, "released": [ { "type": "date" } ], "title": [{ "type": "token" }, { "type": "string", "analyzer": "lucene.keyword", "searchAnalyzer": "lucene.keyword" }] } } } [Next] をクリックします。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックス構成を開始します。
ページで次の選択を行い、[]Next をクリックします。
Search Type | Atlas Searchインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定します。
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
Atlas Search インデックスを定義します。
次のインデックス定義では、 title
フィールドを次のタイプとしてインデックス化します。
インデックスを作成するには、 インターフェースで または を使用できます。Atlas SearchVisual EditorAtlas SearchJSON EditorAtlas user
[Refine Your Index] をクリックします。
Index Configurationsセクションで、Dynamic Mapping を無効に切り替える。
Field Mappingsセクションで、 Add FieldをクリックしてAdd Field Mappingウィンドウを表示します。
[Customized Configuration] をクリックします。
Field Nameドロップダウンから
title
を選択します。Data TypeドロップダウンからTokenを選択します。
[ Token Propertiesを展開し、 Normalizerドロップダウンから [
lowercase
] を選択します。[Add] をクリックします。
手順dとeを繰り返します。
Data TypeドロップダウンからStringを選択します。
[Add] をクリックします。
デフォルトのインデックス定義を、以下の定義で置き換えます。
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": [{ 6 "type": "token", 7 "normalizer": "lowercase" 8 },{ 9 "type": "string" 10 }] 11 } 12 } 13 } [Next] をクリックします。
検索結果を並べ替える
➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。
検索結果は複数の方法で並べ替えることができます。 このセクションでは、Atlas クラスターに接続し、 sample_mflix.movies
コレクション内のインデックス付きフィールドに対してサンプル クエリを実行します。
数字を並べ替える
サンプル クエリの$search
ステージでは、 sort
オプションを使用して Atlas Search の結果をインデックス付き数値フィールドでソートします。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
[ { "$search": { "index": "sort-tutorial", "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 ... ...
クエリ結果を展開します。
Search Testerでは、返されるドキュメント内のすべてのフィールドが表示されない場合があります。 クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。
mongosh
内のクラスターに接続します。
ターミナル ウィンドウでmongosh
を開き、クラスターに接続します。 接続の詳細な手順については、「 mongosh
経由での接続 」を参照してください。
sample_mflix
データベースを使用します。
mongosh
プロンプトで次のコマンドを実行します。
use sample_mflix
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
$search
ステージでは、awards.wins
フィールドを検索し、結果を降順でソートします。$limit
ステージを使用して、出力を5
の結果に制限します。$project
ステージでは、title
とawards.wins
を除くすべてのフィールドが除外されます。
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "index": "sort-tutorial", 5 "range": { 6 "path": "awards.wins", 7 "gte": 10 8 }, 9 "sort": { 10 "awards.wins": -1, 11 } 12 } 13 }, 14 { 15 $limit: 5 16 }, 17 { 18 "$project": { 19 "_id": 0, 20 "title": 1, 21 "awards.wins": 1 22 } 23 } 24 ])
[ { 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 のクラスターに接続します。
MongoDB Compass を開き、クラスターに接続します。 接続の詳細な手順については、「 Compass 経由での接続 」を参照してください。
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
$search
ステージでは、awards.wins
フィールドを検索し、結果を降順でソートします。$limit
ステージを使用して、出力を5
の結果に制限します。$project
ステージでは、title
とawards.wins
を除くすべてのフィールドが除外されます。
MongoDB Compass でこのクエリを実行するには:
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。
パイプラインステージクエリ$search
{ index: "sort-tutorial", "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 } } ]
Program.cs
ファイルにクエリを作成します。
Program.cs
ファイルの内容を、次のコードで置き換えます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public 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 = "sort-tutorial" 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 [ ]49 public class MovieDocument 50 { 51 [ ]52 public ObjectId Id { get; set; } 53 public string Title { get; set; } 54 public Award Awards { get; set; } 55 } 56 57 public class Award 58 { 59 [ ]60 public int Wins { get; set; } 61 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
Program.cs
ファイルをコンパイルして実行します。
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 } }
以下のコードをコピーして、sort-by-numbers.go
ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 package main 2 3 import ( 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 12 func 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.D{ 25 {"index", "sort-tutorial"}, 26 {"range", bson.D{ 27 {"path", "awards.wins"}, 28 {"gte", 10}, 29 }}, 30 {"sort", bson.D{{"awards.wins", -1}}}, 31 }}} 32 limitStage := bson.D{{"$limit", 5}} 33 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"awards.wins", 1}, {"_id", 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 }
注意
サンプルを実行する前に、<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
SortByNumbers.java
という名前のファイルを作成します。次のコードをコピーして、
SortByNumbers.java
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import java.util.Arrays; 2 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import com.mongodb.client.MongoClient; 9 import com.mongodb.client.MongoClients; 10 import com.mongodb.client.MongoCollection; 11 import com.mongodb.client.MongoDatabase; 12 import org.bson.Document; 13 14 public class SortByNumbers { 15 public static void main( String[] args ) { 16 // define query 17 Document agg = 18 new Document("$search", 19 new Document("index", "sort-tutorial") 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; サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。SortByNumbers.java
ファイルをコンパイルして実行します。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}}
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
SortByNumbers.kt
という名前のファイルを作成します。次のコードをコピーして、
SortByNumbers.kt
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
クエリに一致するドキュメントを
AggregateFlow
インスタンスから出力します。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun 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", "sort-tutorial") 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 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。SortByNumbers.kt
ファイルを実行します。IDE で
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}}}}
以下のコードをコピーして、sort-by-numbers.js
ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
MongoDB の Node.js ドライバーである
mongodb
をインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployments connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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': 'sort-tutorial', 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 } 51 run().catch(console.dir);
注意
サンプルを実行する前に、<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
次のコマンドを実行して、コレクションをクエリします。
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 } }
以下のコードをコピーして、sort-by-numbers.py
ファイルに貼り付けます。
次のコード例では、次を行います。
pymongo
、MongoDB の Python ドライバー、およびDNSシード リスト接続文字列を使用してpymongo
をAtlas
に接続するために必要なdns
モジュールをインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次のクエリは、結果を数値フィールドでソートする方法を示しています。 範囲演算子を使用して、10 個以上の賞を受賞した映画を検索し、結果を数値フィールド値で降順にソートします。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$search': { 10 'index': 'sort-tutorial', 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 28 result = client['sample_mflix']['movies'].aggregate(pipeline) 29 30 # print results 31 for i in result: 32 print(i)
注意
サンプルを実行する前に、<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
次のコマンドを実行して、コレクションをクエリします。
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}}
日付を並べ替え
サンプル クエリの$search
ステージでは、 sort
オプションを使用して Atlas Search の結果をインデックス付き日付フィールドでソートします。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックス付き日付フィールドに対して Atlas Search クエリを実行し、結果を並べ替えます。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
[ { $search: { "index": "sort-tutorial", "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 ...
クエリ結果を展開します。
Search Testerでは、返されるドキュメント内のすべてのフィールドが表示されない場合があります。 クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。
mongosh
内のクラスターに接続します。
ターミナル ウィンドウでmongosh
を開き、クラスターに接続します。 接続の詳細な手順については、「 mongosh
経由での接続 」を参照してください。
sample_mflix
データベースを使用します。
mongosh
プロンプトで次のコマンドを実行します。
use sample_mflix
インデックス付き日付フィールドに対して Atlas Search クエリを実行し、結果を並べ替えます。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
ステージでは、
$search
フィールドとtitle
released
フィールドを検索し、その結果を フィールドで降順にソートします。released
$limit
ステージを使用して、出力を5
の結果に制限します。$project
stageを次のように設定します。title
とreleased
を除くすべてのフィールドを除外します。score
という名前のフィールドを追加します。
1 db.movies.aggregate([ 2 { 3 $search: { 4 "index": "sort-tutorial", 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 のクラスターに接続します。
MongoDB Compass を開き、クラスターに接続します。 接続の詳細な手順については、「 Compass 経由での接続 」を参照してください。
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果を非常に高速にソートします。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
ステージでは、
$search
フィールドとtitle
released
フィールドを検索し、その結果を フィールドで降順にソートします。released
$limit
ステージを使用して、出力を5
の結果に制限します。$project
stageを次のように設定します。title
とreleased
を除くすべてのフィールドを除外します。score
という名前のフィールドを追加します。
MongoDB Compass でこのクエリを実行するには:
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。
パイプラインステージクエリ$search
{ "index": "sort-tutorial", "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 }
Program.cs
ファイルにクエリを作成します。
Program.cs
ファイルの内容を、次のコードで置き換えます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public 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 = "sort-tutorial" 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 [ ]55 public class MovieDocument 56 { 57 [ ]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 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
Program.cs
ファイルをコンパイルして実行します。
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 }
以下のコードをコピーして、sort-by-date.go
ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), 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{{"$search", bson.M{ 26 "index": "sort-tutorial", 27 "compound": bson.M{ 28 "filter": bson.A{ 29 bson.M{ 30 "wildcard": bson.D{ 31 {"path", "title"}, 32 {"query", "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{{"released", -1}}, 44 }}} 45 46 limitStage := bson.D{{"$limit", 5}} 47 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"score", bson.D{{"$meta", "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 }
注意
サンプルを実行する前に、<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
次のコマンドを実行して、コレクションをクエリします。
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}]
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
SortByDate.java
という名前のファイルを作成します。次のコードをコピーして、
SortByDate.java
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 import java.time.Instant; 14 import java.util.Date; 15 16 public class SortByDate { 17 public static void main( String[] args ) { 18 // define query 19 Document agg = 20 new Document("$search", 21 new Document("index", "sort-tutorial") 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; サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。SortDateForSpeed.java
ファイルをコンパイルして実行します。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}
インデックス付きフィールドに対して Atlas Search クエリを実行し、結果をソートします。
SortByDate.kt
という名前のファイルを作成します。次のコードをコピーして、
SortByDate.kt
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
クエリに一致するドキュメントを
AggregateFlow
インスタンスから出力します。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 import java.time.Instant 8 import java.util.* 9 10 fun 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", "sort-tutorial") 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 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。SortByDate.kt
ファイルを実行します。IDE で
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}}
以下のコードをコピーして、sort-by-date.js
ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
MongoDB の Node.js ドライバーである
mongodb
をインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployments connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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: "sort-tutorial", 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 } 41 run().catch(console.dir);
注意
サンプルを実行する前に、<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
次のコマンドを実行して、コレクションをクエリします。
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 }
以下のコードをコピーして、sort-by-date.py
ファイルに貼り付けます。
次のコード例では、次を行います。
pymongo
、MongoDB の Python ドライバー、およびDNSシード リスト接続文字列を使用してpymongo
をAtlas
に接続するために必要なdns
モジュールをインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次のクエリは、複合クエリを実行し、結果を日付フィールドでソートする方法を示しています。 次の演算子を使用します。
ワイルドカード演算子を使用すると、
Summer
で始まる映画タイトルを検索できます。near演算子を使用すると、2014 年 4 月 18 日の前後で公開された映画を検索できます。
注意
日付フィールドで
pivot
を使用する場合、その測定単位はミリ秒単位になります。 Atlas Search は、日付フィールドが指定された日付にどれだけ近いかに基づいて、各ドキュメントのスコアを計算します。 詳しくは、の近くを参照してください。
クエリは、次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import datetime 2 import pymongo 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient('<connection-string>') 6 7 # define pipeline 8 pipeline = [ 9 {'$search': { 10 'index': 'sort-tutorial', 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 24 result = client['sample_mflix']['movies'].aggregate(pipeline) 25 26 # print results 27 for i in result: 28 print(i)
注意
サンプルを実行する前に、<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
次のコマンドを実行して、コレクションをクエリします。
python sort-date-for-speed.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}
文字列のソート
サンプル クエリの$search
ステージでは、 sort
オプションを使用してAtlas Searchの結果をインデックス付きstringフィールドでソートします。