Atlas Search クイック スタート
Atlas Search は、 MongoDB Atlasに組み込まれた全文検索で、関連性ベースのアプリ機能を構築するためのシームレスでスケーラブルなエクスペリエンスを提供します。このクイック スタートでは、次の手順で開始する方法について説明します。
サンプルコレクションに Atlas Searchインデックスを作成します。
コレクションを検索するための Atlas Search クエリを作成します。次の方法を学習します:
基本的なクエリを実行して、フィールド内のタームを検索する
演算子を使用して検索を絞り込みます
結果を処理するための検索オプションの追加
所要時間: 15 分
Atlas Search インデックスの作成
Atlas Searchインデックスは、 簡単に検索可能な形式でデータを分類するデータ構造です。タームを、そのタームを含むドキュメントとマッピングして、クエリ時にドキュメントを高速に取得できるようにします。
Atlas Search を使用してデータをクエリするには、Atlas Searchインデックスを構成する必要があります。データのソートやフィルタリングによく使用するフィールドはインデックスことをお勧めします。
詳細については、「Atlas Search インデックスの管理」を参照してください。
このセクションでは、 映画のサンプルコレクションに Atlas Searchインデックスを作成します。 Atlas Searchインデックスは、Atlas クラスターまたはローカル コンピューターでホストされている配置で作成できます。
Atlas クラスターを設定します。
Atlas クラスターがまだない場合は、 無料の M 0クラスターを作成します。 Atlas クラスターの作成の詳細については、「 クラスターの作成 」を参照してください。
注意
既存のクラスターを使用している場合は、Atlas プロジェクトへの
Project Data Access Admin
以上のアクセス権が必要です。新しいクラスターを作成する場合は、必要な権限がデフォルトで付与されます。
プロジェクトごとに作成できる
M0
無料クラスターは 1 つだけです。このクイック スタートのサンプルデータセットをまだクラスターにロードしていない場合は、
sample_mflix
サンプルデータベースをクラスターにロードします。sample_mflix
sample_mflix
データセットをすでに読み込んでいる場合は、embedded_movies
sample_mflix
sample_mflix
データベースに コレクションが含まれていることを確認します。一致しない場合は、 データベースを削除し、 データセットを再読み込みします。サンプルデータセットのロードが完了するまでに数分かかる場合があります。
左側のサイドバーで、[ Atlas Search ] をクリックします。 Select data sourceメニューからクラスターを選択し、 Go to Atlas Searchをクリックします。
Atlas Searchインデックスを作成します。
➤ [ 言語を選択 ] ドロップダウン メニューを使用して、このチュートリアルのクライアントを設定します。
サンプル データの読み込みが完了したら、 Create Search Indexをクリックします。
ページで次の選択を行い、Next をクリックしてください。
Search Type
Atlas Search のインデックスタイプを選択します。
Index Name and Data Source
以下の情報を指定してください。
Index Name:
default
Database and Collection:
sample_mflix
movies
Configuration Method
For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor.インデックスを定義します。
次のインデックス定義は、
movies
コレクション内のフィールドを動的にインデックス化します。movies
コレクションの"default"
インデックス定義を確認します。インデックスの定義を確認します。
インデックス定義は、次のようになります。
{ "mappings": { "dynamic": true } } 上記のインデックス定義は、
movies
コレクション内の各ドキュメントでサポートされているタイプのフィールドを動的にインデックス化します。[Next] をクリックします。
[Create Search Index] をクリックします。
インデックスの作成が完了するまで待ちます。
インデックスの構築には約 1 分かかります。 作成している間、 Status列には
Build in Progress
と表示されます。 作成が完了すると、 Status列にはActive
と表示されます。
mongosh
を使用して Atlas クラスターに接続します。ターミナル ウィンドウで
mongosh
を開き、Atlas クラスターに接続します。 接続の詳細な手順については、「 mongosh 経由での接続 」を参照してください。インデックスを作成するコレクションを含むデータベースに切り替えます。
例
use sample_mflix switched to db sample_mflix db.collection.createSearchIndex()
メソッドを実行してインデックスを作成します。db.movies.createSearchIndex( "default", { mappings: { dynamic: true } } ) default
MongoDB Compass経由で Atlas クラスターに接続します。
Compass を開き、Atlas クラスターに接続します。詳しくは、「 Compass 経由で接続 」を参照してください。
Atlas Searchインデックスを作成します。
[ Indexesタブをクリックし、[ ] を選択します。Search Indexes
[ Create Indexをクリックして、インデックス作成ダイアログボックスを開きます。
インデックスの名前を指定します。
Atlas Searchインデックスの名前は、デフォルトで
default
です。この名前を維持する場合、インデックスは、演算子に別のindex
オプションを指定していない Atlas Search クエリのデフォルトの検索インデックスになります。複数のインデックスを作成する場合は、インデックス間で一貫した記述的な命名規則を維持することをお勧めします。JSON Atlas Searchインデックス定義 を指定します。
1 { 2 "analyzer": "<analyzer-for-index>", 3 "searchAnalyzer": "<analyzer-for-query>", 4 "mappings": { 5 "dynamic": <boolean>, 6 "fields": { <field-definition> } 7 }, 8 "numPartitions": <integer>, 9 "analyzers": [ <custom-analyzer> ], 10 "storedSource": <boolean> | { 11 <stored-source-definition> 12 }, 13 "synonyms": [ 14 { 15 <synonym-mapping-definition> 16 } 17 ] 18 } 19 [Create Search Index] をクリックします。
.NET/ C#プロジェクトを設定して初期化します。
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart dotnet new console # Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver インストール手順の詳細については、 MongoDB C# ドライバーのドキュメント を参照してください。
インデックスを定義します。
次のコードを
Program.cs
ファイルに貼り付けます。Program.cs1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your Atlas Search index 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", true } 19 } 20 } 21 }); 22 23 var result = collection.SearchIndexes.CreateOne(index); 24 Console.WriteLine(result); 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
dotnet run Program.cs default
Goモジュールを設定して初期化します。
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart go mod init atlas-search-quickstart # Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo インストール手順の詳細については、 MongoDB Go ドライバーのドキュメント を参照してください。
インデックスを定義します。
次のコードを
create-index.go
という名前のファイルに貼り付けます。create-index.go1 package main 2 3 import ( 4 "context" 5 "log" 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 12 func main() { 13 ctx := context.Background() 14 15 // Replace the placeholder with your Atlas connection string 16 const uri = "<connection-string>" 17 18 // Connect to your Atlas cluster 19 clientOptions := options.Client().ApplyURI(uri) 20 client, err := mongo.Connect(clientOptions) 21 if err != nil { 22 log.Fatalf("failed to connect to the server: %v", err) 23 } 24 defer func() { _ = client.Disconnect(ctx) }() 25 26 // Set the namespace 27 coll := client.Database("sample_mflix").Collection("movies") 28 29 // Define a simple Atlas Search index 30 indexName := "default" 31 32 // Create the default definition for search index 33 definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}} 34 indexModel := mongo.SearchIndexModel{ 35 Definition: definition, 36 Options: options.SearchIndexes().SetName(indexName), 37 } 38 39 // Create the index 40 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel) 41 if err != nil { 42 log.Fatalf("failed to create the search index: %v", err) 43 } 44 log.Println("New search index named " + searchIndexName + " is building.") 45 } 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
go run create-index.go
Javaドライバー バージョン 4.11 以降をJavaプロジェクトの依存関係として追加します 。パッケージマネージャーに応じて、次のいずれかのタブを選択します。
Maven を使用している場合は、プロジェクトの
pom.xml
ファイルのdependencies
配列に次の依存関係を追加します。pom.xml<dependencies> <!-- MongoDB Java Sync Driver v4.11.0 or later --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>[4.11.0,)</version> </dependency> </dependencies> Gradle を使用している場合は、プロジェクトの
build.gradle
ファイルのdependencies
配列に以下を追加します。build.groupledependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)' } パッケージマネージャーを実行して、プロジェクトに依存関係をインストールします。
詳しいインストール手順やバージョンの互換性については MongoDB Java Driver のドキュメントを参照ください。
インデックスを定義します。
次の例を
CreateIndex.java
という名前のファイルに貼り付けます。CreateIndex.java1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public class CreateIndex { 8 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 12 try (MongoClient mongoClient = MongoClients.create(uri)) { 13 // set namespace 14 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 15 MongoCollection<Document> collection = database.getCollection("movies"); 16 17 Document index = new Document("mappings", 18 new Document("dynamic", true)); 19 collection.createSearchIndex(index); 20 } 21 } 22 } 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true
MongoDB Kotlin コルーチン ドライバーをインストールします。
新しいKotlinプロジェクトを作成し、 MongoDB Kotlinコルーチン ドライバーのドキュメントをインストールします。
インデックスを定義します。
CreateIndex.kt
というファイルを作成します。以下のコードをコピーして、ファイルに貼り付けます。CreateIndex.kt1 import com.mongodb.MongoException 2 import com.mongodb.client.model.SearchIndexModel 3 import com.mongodb.client.model.SearchIndexType 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // Replace the placeholder with your MongoDB deployment's connection string 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 val searchIdx = Document( 15 "mappings", 16 Document("dynamic", true) 17 ) 18 runBlocking { 19 try { 20 val result = collection.createSearchIndex("default", searchIdx) 21 println("Index created: $result") 22 } catch (e: MongoException) { 23 println("Failed to create search index: ${e.message}") 24 } finally { 25 mongoClient.close() 26 } 27 } 28 } 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true IDE で
CreateIndex.kt
ファイルを実行します。
Node.js プロジェクトを初期化します。
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart npm init -y # Add the MongoDB Node.js Driver to your project npm install mongodb インストール手順の詳細については、 MongoDB Node ドライバー のドキュメントを参照してください。
インデックスを定義します。
次のコードを
create-index.js
という名前のファイルに貼り付けます。create-index.js1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 12 // set namespace 13 const database = client.db("sample_mflix"); 14 const collection = database.collection("movies"); 15 16 // define your Atlas Search index 17 const index = { 18 name: "default", 19 definition: { 20 /* search index definition fields */ 21 "mappings": { 22 "dynamic": true 23 } 24 } 25 } 26 27 // run the helper method 28 const result = await collection.createSearchIndex(index); 29 console.log(result); 30 } finally { 31 await client.close(); 32 } 33 } 34 35 run().catch(console.dir); 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
node create-index.js default
MongoDB Pythonドライバーをインストールします。
pip install pymongo インストール手順の詳細については、 「 MongoDB Pythonドライバー(PyMongo) 」を参照してください。
インデックスを定義します。
次のコードを
create_index.py
という名前のファイルに貼り付けます。create_index.py1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your Atlas Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": True 17 }, 18 }, 19 name="default", 20 ) 21 22 # create the index 23 result = collection.create_search_index(model=search_index_model) 24 print(result) 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
python create_index.py default
依存関係をインストールします。
Homebrew を使用する場合は、ターミナルで次のコマンドを実行できます。
brew install mongodb-atlas-cli その他のオペレーティング システムへのインストール手順については、「 Atlas CLI のインストール 」を参照してください。
Docker では、MongoDB イメージをプルしてキャッシュするためにネットワーク接続が必要です。
MacOS または Windows の場合は、 Docker Desktop v4.31 + をインストールします。
Linux の場合は、 Docker Engine v27.0 + をインストールします。
MongoDB データベースツールをインストールします。
サンプルデータを読み込むために使用する コマンドにアクセスするには、 MongoDBコマンドラインDatabase Toolsをインストールする必要があります。
mongorestore
Atlas のローカル配置を設定します。
Atlas アカウントをお持ちでない場合は、ターミナルで
atlas setup
を実行するか、新しいアカウントを作成してください。atlas deployments setup
を実行し、プロンプトに従ってローカル配置を作成します。 配置への接続を求められたら、skip
を選択します。詳細な手順については、「ローカル Atlas 配置の作成 」を参照してください。
Atlas Searchインデックスを作成します。
➤ [ 言語を選択 ] ドロップダウン メニューを使用して、このチュートリアルのクライアントを設定します。
サンプル データの読み込みが完了したら、 Create Search Indexをクリックします。
ページで次の選択を行い、Next をクリックしてください。
Search Type
Atlas Search のインデックスタイプを選択します。
Index Name and Data Source
以下の情報を指定してください。
Index Name:
default
Database and Collection:
sample_mflix
movies
Configuration Method
For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor.インデックスを定義します。
次のインデックス定義は、
movies
コレクション内のフィールドを動的にインデックス化します。movies
コレクションの"default"
インデックス定義を確認します。インデックスの定義を確認します。
インデックス定義は、次のようになります。
{ "mappings": { "dynamic": true } } 上記のインデックス定義は、
movies
コレクション内の各ドキュメントでサポートされているタイプのフィールドを動的にインデックス化します。[Next] をクリックします。
[Create Search Index] をクリックします。
インデックスの作成が完了するまで待ちます。
インデックスの構築には約 1 分かかります。 作成している間、 Status列には
Build in Progress
と表示されます。 作成が完了すると、 Status列にはActive
と表示されます。
mongosh
を使用して Atlas クラスターに接続します。ターミナル ウィンドウで
mongosh
を開き、Atlas クラスターに接続します。 接続の詳細な手順については、「 mongosh 経由での接続 」を参照してください。インデックスを作成するコレクションを含むデータベースに切り替えます。
例
use sample_mflix switched to db sample_mflix db.collection.createSearchIndex()
メソッドを実行してインデックスを作成します。db.movies.createSearchIndex( "default", { mappings: { dynamic: true } } ) default
MongoDB Compass経由で Atlas クラスターに接続します。
Compass を開き、Atlas クラスターに接続します。詳しくは、「 Compass 経由で接続 」を参照してください。
Atlas Searchインデックスを作成します。
[ Indexesタブをクリックし、[ ] を選択します。Search Indexes
[ Create Indexをクリックして、インデックス作成ダイアログボックスを開きます。
インデックスの名前を指定します。
Atlas Searchインデックスの名前は、デフォルトで
default
です。この名前を維持する場合、インデックスは、演算子に別のindex
オプションを指定していない Atlas Search クエリのデフォルトの検索インデックスになります。複数のインデックスを作成する場合は、インデックス間で一貫した記述的な命名規則を維持することをお勧めします。JSON Atlas Searchインデックス定義を指定します。
1 { 2 "analyzer": "<analyzer-for-index>", 3 "searchAnalyzer": "<analyzer-for-query>", 4 "mappings": { 5 "dynamic": <boolean>, 6 "fields": { <field-definition> } 7 }, 8 "numPartitions": <integer>, 9 "analyzers": [ <custom-analyzer> ], 10 "storedSource": <boolean> | { 11 <stored-source-definition> 12 }, 13 "synonyms": [ 14 { 15 <synonym-mapping-definition> 16 } 17 ] 18 } 19 [Create Search Index] をクリックします。
.NET/ C#プロジェクトを設定して初期化します。
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart dotnet new console # Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver インストール手順の詳細については、 MongoDB C# ドライバーのドキュメント を参照してください。
インデックスを定義します。
次のコードを
Program.cs
ファイルに貼り付けます。Program.cs1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_mflix"); 10 var collection = db.GetCollection<BsonDocument>("movies"); 11 12 // define your Atlas Search index 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", true } 19 } 20 } 21 }); 22 23 var result = collection.SearchIndexes.CreateOne(index); 24 Console.WriteLine(result); 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
dotnet run Program.cs default
Goモジュールを設定して初期化します。
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart go mod init atlas-search-quickstart # Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo インストール手順の詳細については、 MongoDB Go ドライバーのドキュメント を参照してください。
インデックスを定義します。
次のコードを
create-index.go
という名前のファイルに貼り付けます。create-index.go1 package main 2 3 import ( 4 "context" 5 "log" 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 12 func main() { 13 ctx := context.Background() 14 15 // Replace the placeholder with your Atlas connection string 16 const uri = "<connection-string>" 17 18 // Connect to your Atlas cluster 19 clientOptions := options.Client().ApplyURI(uri) 20 client, err := mongo.Connect(clientOptions) 21 if err != nil { 22 log.Fatalf("failed to connect to the server: %v", err) 23 } 24 defer func() { _ = client.Disconnect(ctx) }() 25 26 // Set the namespace 27 coll := client.Database("sample_mflix").Collection("movies") 28 29 // Define a simple Atlas Search index 30 indexName := "default" 31 32 // Create the default definition for search index 33 definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}} 34 indexModel := mongo.SearchIndexModel{ 35 Definition: definition, 36 Options: options.SearchIndexes().SetName(indexName), 37 } 38 39 // Create the index 40 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel) 41 if err != nil { 42 log.Fatalf("failed to create the search index: %v", err) 43 } 44 log.Println("New search index named " + searchIndexName + " is building.") 45 } 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
go run create-index.go
Javaドライバー バージョン 4.11 以降をJavaプロジェクトの依存関係として追加します 。パッケージマネージャーに応じて、次のいずれかのタブを選択します。
Maven を使用している場合は、プロジェクトの
pom.xml
ファイルのdependencies
配列に次の依存関係を追加します。pom.xml<dependencies> <!-- MongoDB Java Sync Driver v4.11.0 or later --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>[4.11.0,)</version> </dependency> </dependencies> Gradle を使用している場合は、プロジェクトの
build.gradle
ファイルのdependencies
配列に以下を追加します。build.groupledependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync:[4.11.0,)' } パッケージマネージャーを実行して、プロジェクトに依存関係をインストールします。
詳しいインストール手順やバージョンの互換性については MongoDB Java Driver のドキュメントを参照ください。
インデックスを定義します。
次の例を
CreateIndex.java
という名前のファイルに貼り付けます。CreateIndex.java1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public class CreateIndex { 8 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 12 try (MongoClient mongoClient = MongoClients.create(uri)) { 13 // set namespace 14 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 15 MongoCollection<Document> collection = database.getCollection("movies"); 16 17 Document index = new Document("mappings", 18 new Document("dynamic", true)); 19 collection.createSearchIndex(index); 20 } 21 } 22 } 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true
MongoDB Kotlin コルーチン ドライバーをインストールします。
新しいKotlinプロジェクトを作成し、 MongoDB Kotlinコルーチン ドライバーのドキュメントをインストールします。
インデックスを定義します。
CreateIndex.kt
というファイルを作成します。以下のコードをコピーして、ファイルに貼り付けます。CreateIndex.kt1 import com.mongodb.MongoException 2 import com.mongodb.client.model.SearchIndexModel 3 import com.mongodb.client.model.SearchIndexType 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // Replace the placeholder with your MongoDB deployment's connection string 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 val searchIdx = Document( 15 "mappings", 16 Document("dynamic", true) 17 ) 18 runBlocking { 19 try { 20 val result = collection.createSearchIndex("default", searchIdx) 21 println("Index created: $result") 22 } catch (e: MongoException) { 23 println("Failed to create search index: ${e.message}") 24 } finally { 25 mongoClient.close() 26 } 27 } 28 } 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true IDE で
CreateIndex.kt
ファイルを実行します。
Node.js プロジェクトを初期化します。
# Create a new directory and initialize the project mkdir atlas-search-quickstart && cd atlas-search-quickstart npm init -y # Add the MongoDB Node.js Driver to your project npm install mongodb インストール手順の詳細については、 MongoDB Node ドライバー のドキュメントを参照してください。
インデックスを定義します。
次のコードを
create-index.js
という名前のファイルに貼り付けます。create-index.js1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 12 // set namespace 13 const database = client.db("sample_mflix"); 14 const collection = database.collection("movies"); 15 16 // define your Atlas Search index 17 const index = { 18 name: "default", 19 definition: { 20 /* search index definition fields */ 21 "mappings": { 22 "dynamic": true 23 } 24 } 25 } 26 27 // run the helper method 28 const result = await collection.createSearchIndex(index); 29 console.log(result); 30 } finally { 31 await client.close(); 32 } 33 } 34 35 run().catch(console.dir); 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
node create-index.js default
MongoDB Pythonドライバーをインストールします。
pip install pymongo インストール手順の詳細については、 「 MongoDB Pythonドライバー(PyMongo) 」を参照してください。
インデックスを定義します。
次のコードを
create_index.py
という名前のファイルに貼り付けます。create_index.py1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 # set namespace 9 database = client["sample_mflix"] 10 collection = database["movies"] 11 12 # define your Atlas Search index 13 search_index_model = SearchIndexModel( 14 definition={ 15 "mappings": { 16 "dynamic": True 17 }, 18 }, 19 name="default", 20 ) 21 22 # create the index 23 result = collection.create_search_index(model=search_index_model) 24 print(result) 接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net 注意
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 接続stringの検索方法について詳しくは、「ドライバー経由で接続 」を参照してください。
接続stringには、次の形式を使用する必要があります。
mongodb://localhost:<port-number>/?directConnection=true インデックスを作成します。
python create_index.py default
Atlas 検索クエリをビルドする
Atlas Search クエリは集計パイプラインステージの形式をとります。 Atlas Search は主に$search
ステージで使用します。このステージはクエリパイプラインの最初のステージである必要があります。このステージは、パイプラインの他のステージと組み合わせて使用することもできます。
Atlas Search クエリを実行すると、Atlas Search は検索インデックスを使用して、コレクションから関連するデータを検索し、取得します。 Atlas Search は、検索結果をさらに絞り込むために使用できる$searchMeta
ステージ、複数のサブパイプライン、およびいくつかのクエリ 演算子とコレクター も備えています。
詳細については、「 クエリとインデックス 」を参照してください。
このセクションでは、インデックス付きコレクションに対してクエリを実行します。
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。
次のクエリをQuery Editor に貼り付け、 の [1]Search Query Editorボタンをクリックします。
1 [ 2 { 3 $search: 4 { 5 text: { 6 query: "baseball", 7 path: "plot" 8 } 9 } 10 } 11 ]
SCORE: 3.8531038761138916 _id: "573a13b3f29313caabd3b409" fullplot: "Three guys, all their lives, have been living in the shadow of bullies…" imdb: Object year: 2006 ... SCORE: 3.6254453659057617 _id: "573a1399f29313caabcee801" plot: "A young boy is bequeathed the ownership of a professional baseball tea..." genres: Array runtime: 119 ... SCORE: 3.6254453659057617 _id: "573a139af29313caabcefe18" plot: "A trained chimpanzee plays third base for a minor-league baseball team..." genres: Array runtime: 94 ... ...
注意
Search Tester では、返されるドキュメント内のすべてのフィールドが表示されない場合があります。クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。
次のクエリをQuery Editor に貼り付け、 の [1]Search Query Editorボタンをクリックします。
1 [ 2 { 3 "$search": { 4 "compound": { 5 "must": [ 6 { 7 "text": { 8 "query": "baseball", 9 "path": "plot" 10 } 11 } 12 ], 13 "mustNot": [ 14 { 15 "text": { 16 "query": ["Comedy", "Romance"], 17 "path": "genres" 18 } 19 } 20 ] 21 } 22 } 23 } 24 ]
SCORE: 3.4706974029541016 _id: "573a1393f29313caabcdca79" title: "The Pride of the Yankees" plot: "The story of the life and career of the famed baseball player, Lou Geh…" genres: ["Biography", "Drama", "Family"] ... SCORE: 3.4706974029541016 _id: "573a1399f29313caabcecef1" title: "The Babe" plot: "Babe Ruth becomes a baseball legend but is unheroic to those who know …" genres: ["Biography", "Drama", "Sport"] ... SCORE: 3.406810760498047 _id: "573a13bdf29313caabd5813d" title: "Sugar" plot: "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in …" genres: ["Drama", "Sport"] ... ...
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
1 [ 2 { 3 "$search": { 4 "compound": { 5 "must": [ 6 { 7 "text": { 8 "query": "baseball", 9 "path": "plot" 10 } 11 } 12 ], 13 "mustNot": [ 14 { 15 "text": { 16 "query": ["Comedy", "Romance"], 17 "path": "genres" 18 } 19 } 20 ] 21 }, 22 "sort": { 23 "released": -1 24 } 25 } 26 } 27 ]
SCORE: 3.173170804977417 _id: "573a13ccf29313caabd832f5" plot: "A sports agent stages an unconventional recruitment strategy to get ta…" title: "Million Dollar Arm" genres: Array (3) released: 2014-05-16T00:00:00.000+00:00 ... SCORE: 3.2858426570892334 _id: "573a13d9f29313caabda97d8" plot: "A Taiwanese high school baseball team travels to Japan in 1931 to comp…" title: "Kano" genres: Array (3) released: 2014-02-27T00:00:00.000+00:00 ... SCORE: 2.4570295810699463 _id: "573a13daf29313caabdad92d" plot: "12-year-old Josh is a mixed race boy and a promising baseball player..." title: "Calloused Hands" genres: Array (1) released: 2013-03-03T00:00:00.000+00:00 ... ...
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
1 db.movies.aggregate([ 2 { 3 $search: 4 { 5 "text": { 6 "query": "baseball", 7 "path": "plot" 8 } 9 } 10 }, 11 { 12 $limit: 3 13 }, 14 { 15 $project: { 16 "_id": 0, 17 "title": 1, 18 "plot": 1 19 } 20 } 21 ])
{ "plot" : "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title" : "The Benchwarmers" } { "plot" : "A young boy is bequeathed the ownership of a professional baseball team.", "title" : "Little Big League" } { "plot" : "A trained chimpanzee plays third base for a minor-league baseball team.", "title" : "Ed" }
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
1 db.movies.aggregate([ 2 { 3 $search: { 4 "compound": { 5 "must": [ 6 { 7 "text": { 8 "query": "baseball", 9 "path": "plot" 10 } 11 } 12 ], 13 "mustNot": [ 14 { 15 "text": { 16 "query": ["Comedy", "Romance"], 17 "path": "genres" 18 } 19 } 20 ] 21 } 22 } 23 }, 24 { 25 $limit: 3 26 }, 27 { 28 $project: { 29 "_id": 0, 30 "title": 1, 31 "plot": 1, 32 "genres": 1 33 } 34 } 35 ])
[ { plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.', genres: [ 'Biography', 'Drama', 'Family' ], title: 'The Pride of the Yankees' }, { plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'The Babe' }, { plot: 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', genres: [ 'Drama', 'Sport' ], title: 'Sugar' } ]
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
1 db.movies.aggregate([ 2 { 3 $search: { 4 "compound": { 5 "must": [ { 6 "text": { 7 "query": "baseball", 8 "path": "plot" 9 } 10 }], 11 "mustNot": [ { 12 "text": { 13 "query": ["Comedy", "Romance"], 14 "path": "genres" 15 } 16 } ] 17 }, 18 "sort": { 19 "released": -1 20 } 21 } 22 }, 23 { 24 $limit: 3 25 }, 26 { 27 $project: { 28 "_id": 0, 29 "title": 1, 30 "plot": 1, 31 "genres": 1, 32 "released": 1 33 } 34 } 35 ])
[ { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: ISODate('2014-05-16T00:00:00.000Z') }, { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: ISODate('2014-02-27T00:00:00.000Z') }, { plot: "12-year-old Josh is a mixed race boy and a promising baseball player...", genres: [ 'Drama' ], title: 'Calloused Hands', released: ISODate('2013-03-03T00:00:00.000Z') } ]
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
MongoDB Compass でこのクエリを実行するには:
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
パイプラインステージクエリ$search
{ "text": { "query": "baseball", "path": "plot" } } $limit
3 $project
{ "_id": 0, "title": 1, "plot": 1, }
Auto Previewを有効にした場合、MongoDB Compass は$project
パイプライン ステージの横に次のドキュメントを表示します。
{ "plot" : "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title" : "The Benchwarmers" } { "plot" : "A young boy is bequeathed the ownership of a professional baseball team.", "title" : "Little Big League" } { "plot" : "A trained chimpanzee plays third base for a minor-league baseball team.", "title" : "Ed" }
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
MongoDB Compassで次のパイプラインステージを更新します。
パイプラインステージ | クエリ | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| ||||||||||||||||||||
|
|
Auto Previewを有効にした場合、MongoDB Compass は$project
パイプライン ステージの横に次のドキュメントを表示します。
{ "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "genres" : [ "Biography", "Drama", "Family" ], "title" : "The Pride of the Yankees" } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "genres" : [ "Biography", "Drama", "Sport" ], "title" : "The Babe" } { "plot" : "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "genres" : [ "Drama", "Sport" ], "title" : "Sugar" }
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
MongoDB Compassで次のパイプラインステージを更新します。
パイプラインステージ | クエリ | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||||||||||||||||
|
|
Auto Previewを有効にした場合、MongoDB Compass は$project
パイプライン ステージの横に次のドキュメントを表示します。
[ { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: 2014-05-16T00:00:00.000+00:00 }, { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: 2014-02-27T00:00:00.000+00:00 }, { plot: "12-year-old Josh is a mixed race boy and a promising baseball player...", genres: [ 'Drama' ], title: 'Calloused Hands', released: 2013-03-03T00:00:00.000+00:00 } ]
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
Program.cs
ファイルの内容を、次のコードで置き換えます。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
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 BasicQuery 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 and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball")) 25 .Project<MovieDocument>(Builders<MovieDocument>.Projection 26 .Include(movie => movie.Plot) 27 .Include(movie => movie.Title) 28 .Exclude(movie => movie.Id)) 29 .Limit(3) 30 .ToList(); 31 32 // print results 33 foreach (var movie in results) 34 { 35 Console.WriteLine(movie.ToJson()); 36 } 37 } 38 } 39 40 [ ]41 public class MovieDocument 42 { 43 [ ]44 public ObjectId Id { get; set; } 45 public string Plot { get; set; } 46 public string Title { get; set; } 47 } <connection-string>
を指定してクエリを実行します。dotnet run Program.cs { "plot" : "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title" : "The Benchwarmers" } { "plot" : "A young boy is bequeathed the ownership of a professional baseball team.", "title" : "Little Big League" } { "plot" : "A trained chimpanzee plays third base for a minor-league baseball team.", "title" : "Ed" }
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
次のコードで
Program.cs
ファイルを変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
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 CompoundQuery 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 // declare data for the compound query 23 string[] genres = { "Comedy", "Romance" }; 24 25 // define and run pipeline 26 var results = moviesCollection.Aggregate() 27 .Search(Builders<MovieDocument>.Search.Compound() 28 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball")) 29 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres)))) 30 .Project<MovieDocument>(Builders<MovieDocument>.Projection 31 .Exclude(movie => movie.Id) 32 .Include(movie => movie.Plot) 33 .Include(movie => movie.Title) 34 .Include(movie => movie.Genres)) 35 .Limit(3) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Plot { get; set; } 52 public string Title { get; set; } 53 public string[] Genres { get; set; } 54 } <connection-string>
を指定してクエリを実行します。dotnet run Program.cs { "plot" : "The story of the life and career of the famed baseball player, Lou Gehrig.", "title" : "The Pride of the Yankees", "genres" : ["Biography", "Drama", "Family"] } { "plot" : "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "title" : "The Babe", "genres" : ["Biography", "Drama", "Sport"] } { "plot" : "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "title" : "Sugar", "genres" : ["Drama", "Sport"] }
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
次のコードで
Program.cs
ファイルを変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
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 SortQuery 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 // declare data for the compound query 23 string[] genres = { "Comedy", "Romance" }; 24 25 // define search options 26 var searchOptions = new SearchOptions<MovieDocument>() 27 { 28 Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released), 29 }; 30 31 // define and run pipeline 32 var results = moviesCollection.Aggregate() 33 .Search(Builders<MovieDocument>.Search.Compound() 34 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball")) 35 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres))), searchOptions) 36 .Project<MovieDocument>(Builders<MovieDocument>.Projection 37 .Exclude(movie => movie.Id) 38 .Include(movie => movie.Plot) 39 .Include(movie => movie.Title) 40 .Include(movie => movie.Genres) 41 .Include(movie => movie.Released)) 42 .Limit(3) 43 .ToList(); 44 45 // print results 46 foreach (var movie in results) 47 { 48 Console.WriteLine(movie.ToJson()); 49 } 50 } 51 } 52 53 [ ]54 public class MovieDocument 55 { 56 [ ]57 public ObjectId Id { get; set; } 58 public string Plot { get; set; } 59 public string Title { get; set; } 60 public string[] Genres { get; set; } 61 public DateTime Released { get; set; } 62 } <connection-string>
を指定してクエリを実行します。dotnet run Program.cs { "plot" : "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.", "title" : "Million Dollar Arm", "genres" : ["Biography", "Drama", "Sport"], "released" : { "$date" : "2014-05-16T00:00:00Z" } } { "plot" : "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.", "title" : "Kano", "genres" : ["Biography", "Drama", "History"], "released" : { "$date" : "2014-02-27T00:00:00Z" } } { "plot" : "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", "title" : "Calloused Hands", "genres" : ["Drama"], "released" : { "$date" : "2013-03-03T00:00:00Z" } }
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
run-query.go
という名前の新しいファイルを作成し、次のコードを貼り付けます。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
1 package main 2 3 import ( 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 13 func main() { 14 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_mflix").Collection("movies") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.D{ 26 {"text", bson.D{ 27 {"path", "plot"}, 28 {"query", "baseball"}, 29 }}, 30 }}} 31 limitStage := bson.D{{"$limit", 3}} 32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}} 33 // run pipeline 34 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 35 if err != nil { 36 panic(err) 37 } 38 // print results 39 var results []bson.D 40 if err = cursor.All(context.TODO(), &results); err != nil { 41 panic(err) 42 } 43 for _, result := range results { 44 fmt.Println(result) 45 } 46 } <connection-string>
を指定してクエリを実行します。go run run-query.go {"plot":"A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.","title":"The Benchwarmers"} {"plot":"A young boy is bequeathed the ownership of a professional baseball team.","title":"Little Big League"} {"plot":"A trained chimpanzee plays third base for a minor-league baseball team.","title":"Ed"}
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
複合クエリを使用するには、
run-query.go
を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
1 package main 2 3 import ( 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 13 func main() { 14 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_mflix").Collection("movies") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.M{ 26 "compound": bson.M{ 27 "must": bson.A{ 28 bson.M{ 29 "text": bson.D{ 30 {"path", "plot"}, {"query", "baseball"}, 31 }, 32 }, 33 }, 34 "mustNot": bson.A{ 35 bson.M{ 36 "text": bson.M{ 37 "path": "genres", "query": []string{"Comedy", "Romance"}, 38 }, 39 }, 40 }, 41 }, 42 }}} 43 limitStage := bson.D{{"$limit", 3}} 44 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"genres", 1}, {"_id", 0}}}} 45 // run pipeline 46 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 47 if err != nil { 48 panic(err) 49 } 50 // print results 51 var results []bson.D 52 if err = cursor.All(context.TODO(), &results); err != nil { 53 panic(err) 54 } 55 for _, result := range results { 56 fmt.Println(result) 57 } 58 } <connection-string>
を指定してクエリを実行します。go run run-query.go {"plot":"The story of the life and career of the famed baseball player, Lou Gehrig.","genres":["Biography","Drama","Family"],"title":"The Pride of the Yankees"} {"plot":"Babe Ruth becomes a baseball legend but is unheroic to those who know him.","genres":["Biography","Drama","Sport"],"title":"The Babe"} {"plot":"Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.","genres":["Drama","Sport"],"title":"Sugar"}
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
run-query.go
並べ替えオプションを追加するには、 を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
1 package main 2 3 import ( 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 13 func main() { 14 var err error 15 // connect to the Atlas cluster 16 ctx := context.Background() 17 client, err := mongo.Connect(options.Client().SetTimeout(5 * time.Second).ApplyURI("<connection-string>")) 18 if err != nil { 19 panic(err) 20 } 21 defer client.Disconnect(ctx) 22 // set namespace 23 collection := client.Database("sample_mflix").Collection("movies") 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.M{ 26 "compound": bson.M{ 27 "must": bson.A{ 28 bson.M{ 29 "text": bson.D{ 30 {"path", "plot"}, {"query", "baseball"}, 31 }, 32 }, 33 }, 34 "mustNot": bson.A{ 35 bson.M{ 36 "text": bson.M{ 37 "path": "genres", "query": []string{"Comedy", "Romance"}, 38 }, 39 }, 40 }, 41 }, 42 "sort": bson.D{ 43 {"released", -1}, 44 }, 45 }}} 46 limitStage := bson.D{{"$limit", 3}} 47 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"plot", 1}, {"genres", 1}, {"released", 1}}}} 48 // run pipeline 49 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 50 if err != nil { 51 panic(err) 52 } 53 // print results 54 var results []bson.D 55 if err = cursor.All(context.TODO(), &results); err != nil { 56 panic(err) 57 } 58 for _, result := range results { 59 fmt.Println(result) 60 } 61 } <connection-string>
を指定してクエリを実行します。go run run-query.go {"plot":"A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.","genres":["Biography","Drama","Sport"],"title":"Million Dollar Arm","released":{"$date":{"$numberLong":"1400198400000"}}} {"plot":"A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.","genres":["Biography","Drama","History"],"title":"Kano","released":{"$date":{"$numberLong":"1393459200000"}}} {"plot":"12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...","genres":["Drama"],"title":"Calloused Hands","released":{"$date":{"$numberLong":"1362268800000"}}}
依存関係をインストールします。
CLASSPATH
に次のライブラリが含まれていることを確認します。
| 4.11.0以降のバージョン |
| 4.11.0以降のバージョン |
| 1.7.30以降のバージョン |
詳しいインストール手順やバージョンの互換性については MongoDB Java Driver のドキュメントを参照ください。
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
RunQuery.java
という名前の新しいファイルを作成し、次のコードを貼り付けます。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
1 import java.util.Arrays; 2 import java.util.List; 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 RunQuery { 15 public static void main( String[] args ) { 16 String uri = "<connection-string>"; 17 18 try (MongoClient mongoClient = MongoClients.create(uri)) { 19 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 20 MongoCollection<Document> collection = database.getCollection("movies"); 21 22 Document textQuery = new Document("query", "baseball").append("path","plot"); 23 24 Document searchStage = new Document("$search", 25 new Document("index", "default") 26 .append("text", textQuery)); 27 28 collection.aggregate(Arrays.asList( 29 searchStage, 30 limit(3), 31 project(fields(excludeId(), include("title", "plot")))) 32 ).forEach(doc -> System.out.println(doc.toJson())); 33 } 34 } 35 } 注意
Maven 環境でサンプル コードを実行するには、 ファイルのインポート ステートメントの上に以下を追加します。
package com.mongodb.drivers; <connection-string>
を指定してクエリを実行します。javac RunQuery.java java RunQuery {"plot": "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.", "title": "The Benchwarmers"} {"plot": "A young boy is bequeathed the ownership of a professional baseball team.", "title": "Little Big League"} {"plot": "A trained chimpanzee plays third base for a minor-league baseball team.", "title": "Ed"}
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
複合クエリを使用するには、
RunQuery.java
を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
1 import java.util.Arrays; 2 import java.util.List; 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 RunQuery { 15 public static void main( String[] args ) { 16 String uri = "<connection-string>"; 17 18 try (MongoClient mongoClient = MongoClients.create(uri)) { 19 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 20 MongoCollection<Document> collection = database.getCollection("movies"); 21 22 Document compound = new Document("must", Arrays.asList( 23 new Document("text", new Document("query", "baseball").append("path", "plot")))) 24 .append("mustNot", Arrays.asList( 25 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")))); 26 27 Document searchStage = new Document("$search", 28 new Document("index", "default") 29 .append("compound", compound)); 30 31 collection.aggregate(Arrays.asList( 32 searchStage, 33 limit(3), 34 project(fields(excludeId(), include("title", "plot", "genres")))) 35 ).forEach(doc -> System.out.println(doc.toJson())); 36 } 37 } 38 } <connection-string>
を指定してクエリを実行します。javac RunQuery.java java RunQuery {"plot": "The story of the life and career of the famed baseball player, Lou Gehrig.", "genres": ["Biography", "Drama", "Family"], "title": "The Pride of the Yankees"} {"plot": "Babe Ruth becomes a baseball legend but is unheroic to those who know him.", "genres": ["Biography", "Drama", "Sport"], "title": "The Babe"} {"plot": "Dominican baseball star Miguel \"Sugar\" Santos is recruited to play in the U.S. minor-leagues.", "genres": ["Drama", "Sport"], "title": "Sugar"}
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
RunQuery.java
並べ替えオプションを追加するには、 を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
1 import java.util.Arrays; 2 import java.util.List; 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 RunQuery { 15 public static void main( String[] args ) { 16 String uri = "<connection-string>"; 17 18 try (MongoClient mongoClient = MongoClients.create(uri)) { 19 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 20 MongoCollection<Document> collection = database.getCollection("movies"); 21 22 Document compound = new Document("must", Arrays.asList( 23 new Document("text", new Document("query", "baseball").append("path", "plot")))) 24 .append("mustNot", Arrays.asList( 25 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")))); 26 27 Document searchStage = new Document("$search", 28 new Document("index", "default") 29 .append("compound", compound) 30 .append("sort", new Document("released", -1))); 31 32 collection.aggregate(Arrays.asList( 33 searchStage, 34 limit(3), 35 project(fields(excludeId(), include("title", "plot", "genres", "released")))) 36 ).forEach(doc -> System.out.println(doc.toJson())); 37 } 38 } 39 } <connection-string>
を指定してクエリを実行します。javac RunQuery.java java RunQuery {"plot": "A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.", "genres": ["Biography", "Drama", "Sport"], "title": "Million Dollar Arm", "released": {"$date": "2014-05-16T00:00:00Z"}} {"plot": "A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.", "genres": ["Biography", "Drama", "History"], "title": "Kano", "released": {"$date": "2014-02-27T00:00:00Z"}} {"plot": "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", "genres": ["Drama"], "title": "Calloused Hands", "released": {"$date": "2013-03-03T00:00:00Z"}}
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
RunQuery.kt
という名前の新しいファイルを作成し、次のコードを貼り付けます。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define query 18 val agg = Document("query", "baseball").append("path","plot") 19 20 // run query and print results 21 val resultsFlow = collection.aggregate<Document>( 22 listOf( 23 eq("\$search", eq("text", agg)), 24 limit(3), 25 project(fields(excludeId(), include("title", "plot"))) 26 ) 27 ) 28 resultsFlow.collect { println(it) } 29 } 30 mongoClient.close() 31 } <connection-string>
を指定してクエリを実行します。IDE で
RunQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., genres=[Biography, Drama, Family], title=The Pride of the Yankees}} Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., genres=[Biography, Drama, Sport], title=The Babe}} Document{{plot=Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues., genres=[Drama, Sport], title=Sugar}}
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
複合クエリを使用するには、
RunQuery.kt
を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define query 18 val compoundQuery = Document( 19 "must", listOf( 20 Document("text", Document("query", "baseball") 21 .append("path", "plot")) 22 ) 23 ) 24 .append( 25 "mustNot", listOf( 26 Document("text", Document("query", listOf("Comedy", "Romance")) 27 .append("path", "genres")) 28 ) 29 ) 30 31 // run query and print results 32 val resultsFlow = collection.aggregate<Document>( 33 listOf( 34 eq("\$search", eq("compound", compoundQuery)), 35 limit(3), 36 project(fields( 37 excludeId(), 38 include("title", "plot", "genres") 39 )) 40 ) 41 ) 42 resultsFlow.collect { println(it) } 43 } 44 mongoClient.close() 45 } <connection-string>
を指定してクエリを実行します。IDE で
RunQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., genres=[Biography, Drama, Family], title=The Pride of the Yankees}} Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., genres=[Biography, Drama, Sport], title=The Babe}} Document{{plot=Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues., genres=[Drama, Sport], title=Sugar}}
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
RunQuery.kt
並べ替えオプションを追加するには、 を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Filters.eq 4 import com.mongodb.client.model.Projections.* 5 import com.mongodb.kotlin.client.coroutine.MongoClient 6 import kotlinx.coroutines.runBlocking 7 import org.bson.Document 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define query 18 val compoundQuery = Document( 19 "must", listOf( 20 Document("text", Document("query", "baseball") 21 .append("path", "plot")) 22 ) 23 ) 24 .append( 25 "mustNot", listOf( 26 Document("text", Document("query", listOf("Comedy", "Romance")) 27 .append("path", "genres")) 28 ) 29 ) 30 31 // sort configuration 32 val sortConfig = Document("released", -1) 33 34 // run query and print results 35 val resultsFlow = collection.aggregate<Document>( 36 listOf( 37 Document("\$search", Document("compound", compoundQuery).append("sort", sortConfig)), 38 limit(3), 39 project(fields( 40 excludeId(), 41 include("title", "plot", "genres", "released") 42 )) 43 ) 44 ) 45 resultsFlow.collect { println(it) } 46 } 47 mongoClient.close() 48 } <connection-string>
を指定してクエリを実行します。IDE で
RunQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{plot=A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball., genres=[Biography, Drama, Sport], title=Million Dollar Arm, released=Thu May 15 19:00:00 CDT 2014}} Document{{plot=A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament., genres=[Biography, Drama, History], title=Kano, released=Wed Feb 26 18:00:00 CST 2014}} Document{{plot=12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ..., genres=[Drama], title=Calloused Hands, released=Sat Mar 02 18:00:00 CST 2013}}
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
run-query.js
という名前の新しいファイルを作成し、次のコードを貼り付けます。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
1 const { MongoClient } = require("mongodb"); 2 3 async function main() { 4 // Replace the placeholder with your connection string 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 try { 9 await client.connect(); 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 const query = [ 14 { 15 $search: 16 { 17 text: { 18 query: "baseball", 19 path: "plot", 20 }, 21 } 22 }, 23 { 24 $limit: 3, 25 }, 26 { 27 $project: { 28 _id: 0, 29 title: 1, 30 plot: 1, 31 }, 32 }, 33 ]; 34 35 const cursor = movies.aggregate(query); 36 await cursor.forEach(doc => console.log(doc)); 37 } finally { 38 await client.close(); 39 } 40 } 41 42 main().catch(console.error); <connection-string>
を指定してクエリを実行します。node run-query.js { plot: 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.', title: 'The Benchwarmers' } { plot: 'A young boy is bequeathed the ownership of a professional baseball team.', title: 'Little Big League' } { plot: 'A trained chimpanzee plays third base for a minor-league baseball team.', title: 'Ed' }
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
複合クエリを使用するには、
run-query.js
を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
1 const { MongoClient } = require("mongodb"); 2 3 async function main() { 4 // Replace the placeholder with your connection string 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 try { 9 await client.connect(); 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 const query = [ 14 { 15 $search: { 16 compound: { 17 must: [ 18 { 19 text: { 20 query: "baseball", 21 path: "plot", 22 } 23 } 24 ], 25 mustNot: [ 26 { 27 text: { 28 query: ["Comedy", "Romance"], 29 path: "genres", 30 }, 31 } 32 ] 33 } 34 } 35 }, 36 { 37 $limit: 3 38 }, 39 { 40 $project: { 41 _id: 0, 42 title: 1, 43 plot: 1, 44 genres: 1 45 } 46 } 47 ]; 48 49 const cursor = movies.aggregate(query); 50 await cursor.forEach(doc => console.log(doc)); 51 } finally { 52 await client.close(); 53 } 54 } 55 56 main().catch(console.error); <connection-string>
を指定してクエリを実行します。node run-query.js { plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.', genres: [ 'Biography', 'Drama', 'Family' ], title: 'The Pride of the Yankees' } { plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'The Babe' } { plot: 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', genres: [ 'Drama', 'Sport' ], title: 'Sugar' }
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
run-query.js
並べ替えオプションを追加するには、 を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
1 const { MongoClient } = require("mongodb"); 2 3 async function main() { 4 // Replace the placeholder with your connection string 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 try { 9 await client.connect(); 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 const query = [ 14 { 15 $search: { 16 compound: { 17 must: [ 18 { 19 text: { 20 query: "baseball", 21 path: "plot", 22 } 23 } 24 ], 25 mustNot: [ 26 { 27 text: { 28 query: ["Comedy", "Romance"], 29 path: "genres", 30 } 31 } 32 ] 33 }, 34 sort: { 35 released: -1 36 } 37 } 38 }, 39 { 40 $limit: 3 41 }, 42 { 43 $project: { 44 _id: 0, 45 title: 1, 46 plot: 1, 47 genres: 1, 48 released: 1 49 } 50 } 51 ]; 52 53 const cursor = movies.aggregate(query); 54 await cursor.forEach(doc => console.log(doc)); 55 } finally { 56 await client.close(); 57 } 58 } 59 60 main().catch(console.error); <connection-string>
を指定してクエリを実行します。node run-query.js { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: 2014-05-16T00:00:00.000Z } { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: 2014-02-27T00:00:00.000Z } { plot: "12-year-old Josh is a mixed race boy and a promising baseball player...", genres: [ 'Drama' ], title: 'Calloused Hands', released: 2013-03-03T00:00:00.000Z }
基本的なクエリを実行します。
テキスト演算子を使用して、基本的な $search
クエリを実行します。
run_query.py
という名前の新しいファイルを作成し、次のコードを貼り付けます。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。$limit ステージと $プロジェクト ステージは、3 ドキュメントと
title
フィールドとplot
フィールドのみを返します。
1 import pymongo 2 3 client = pymongo.MongoClient('<connection-string>') 4 result = client['sample_mflix']['movies'].aggregate([ 5 { 6 '$search': 7 { 8 'text': { 9 'query': 'baseball', 10 'path': 'plot' 11 } 12 } 13 }, 14 { 15 '$limit': 3 16 }, 17 { 18 '$project': { 19 '_id': 0, 20 'title': 1, 21 'plot': 1 22 } 23 } 24 ]) 25 26 for i in result: 27 print(i) <connection-string>
を指定してクエリを実行します。python run_query.py {'plot': 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.', 'title': 'The Benchwarmers'} {'plot': 'A young boy is bequeathed the ownership of a professional baseball team.', 'title': 'Little Big League'} {'plot': 'A trained chimpanzee plays third base for a minor-league baseball team.', 'title': 'Ed'}
検索を微調整します。
Atlas Search には、複雑なクエリを作成し、ユースケースのより具体的な結果を取得するために使用できる演算子がいくつか用意されています。複合演算子を使用して複数の演算子を 1 つのクエリに結合するには、$search
クエリを更新します。
複合クエリを使用するには、
run_query.py
を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
フィールドのみが返されます。
1 import pymongo 2 3 client = pymongo.MongoClient('<connection-string>') 4 result = client['sample_mflix']['movies'].aggregate([ 5 { 6 '$search': { 7 'compound': { 8 'must': [ 9 { 10 'text': { 11 'query': 'baseball', 12 'path': 'plot' 13 } 14 } 15 ], 16 'mustNot': [ 17 { 18 'text': { 19 'query': ['Comedy', 'Romance'], 20 'path': 'genres' 21 } 22 } 23 ] 24 } 25 } 26 }, 27 { 28 '$limit': 3 29 }, 30 { 31 '$project': { 32 '_id': 0, 33 'title': 1, 34 'plot': 1, 35 'genres': 1 36 } 37 } 38 ]) 39 40 for i in result: 41 print(i) <connection-string>
を指定してクエリを実行します。python run_query.py {'plot': 'The story of the life and career of the famed baseball player, Lou Gehrig.', 'genres': ['Biography', 'Drama', 'Family'], 'title': 'The Pride of the Yankees'} {'plot': 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', 'genres': ['Biography', 'Drama', 'Sport'], 'title': 'The Babe'} {'plot': 'Dominican baseball star Miguel "Sugar" Santos is recruited to play in the U.S. minor-leagues.', 'genres': ['Drama', 'Sport'], 'title': 'Sugar'}
結果を処理します。
Atlas Search には、Atlas Search クエリ結果をさらに処理するために使用できるいくつかの検索オプションが用意されています。クエリにソートオプションを追加すると、結果が特定の順序で表示されます。
run_query.py
並べ替えオプションを追加するには、 を変更します。このクエリには次の検索条件があります。
plot
フィールドには {wordbaseball
が含まれている必要があります。genres
フィールドにはComedy
もRomance
も含めることはできません。released
日付フィールドで結果を降順で並べ替えます。 Atlas Search は最新の映画が最初に返されます。$limit ステージと $プロジェクト ステージでは、3 ドキュメントと
title
、plot
、genres
、released
フィールドのみが返されます。
1 import pymongo 2 3 client = pymongo.MongoClient('<connection-string>') 4 result = client['sample_mflix']['movies'].aggregate([ 5 { 6 '$search': { 7 'compound': { 8 'must': [ 9 { 10 'text': { 11 'query': 'baseball', 12 'path': 'plot' 13 } 14 } 15 ], 16 'mustNot': [ 17 { 18 'text': { 19 'query': ['Comedy', 'Romance'], 20 'path': 'genres' 21 } 22 } 23 ] 24 }, 25 'sort': { 26 'released': -1 27 } 28 } 29 }, 30 { 31 '$limit': 3 32 }, 33 { 34 '$project': { 35 '_id': 0, 36 'title': 1, 37 'plot': 1, 38 'genres': 1, 39 'released': 1 40 } 41 } 42 ]) 43 44 for i in result: 45 print(i) <connection-string>
を指定してクエリを実行します。python run_query.py {'plot': 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', 'genres': ['Biography', 'Drama', 'Sport'], 'title': 'Million Dollar Arm', 'released': datetime.datetime(2014, 5, 16, 0, 0)} {'plot': 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', 'genres': ['Biography', 'Drama', 'History'], 'title': 'Kano', 'released': datetime.datetime(2014, 2, 27, 0, 0)} {'plot': "12-year-old Josh is a mixed race boy and a promising baseball player...", 'genres': ['Drama'], 'title': 'Calloused Hands', 'released': datetime.datetime(2013, 3, 3, 0, 0)}
学び続ける
オートコンプリートおよび部分一致クエリの実行
Atlas Search を使用して、部分的な単語の結果を返すオートコンプリート クエリと部分クエリを実行できます。これは、アプリケーションの 検索フィールドに入力される文字が多くなるほど、結果を検索する精度が向上するのに役立ちます。オートコンプリート演算子を使用するには、フィールドを Atlas Search オートコンプリート タイプとしてインデックス必要があります。
ファセットで検索結果をグループ化
Atlas Search を使用して、検索結果を string、日付、または数値でグループ化するファセットクエリを実行できます。ファセットコレクターを使用するには、ファセット定義を持つインデックスを作成する必要があります。
開始するには、「 Atlas Searchでファセットの使用方法 」を参照してください。
Atlas Search Playground の使用
Atlas Searchboolean
では、インデックス付きの 、date
、number
、objectId
、string
フィールド値に対して昇順または降順で結果をソートできます。詳しくは、「 Atlas 検索結果の並べ替え 」を参照してください。
コースで学ぶ
Atlas Search について詳細は、MongoDB University の Atlas Search コースユニット 1 を受講してください。2.25 時間のユニットには、Atlas Search の概要、Atlas Search インデックスの作成方法、さまざまな演算子での $search
の使用方法、および検索ファセットの生成方法に関するレッスンが含まれています。
ビデオで学ぶ
Atlas Search について詳しくは、次のビデオもご覧ください。
Atlas と Atlas Search の概要を視聴した後に、対象のデータに対して Atlas Search の設定を開始します。このビデオでは、クラスターにサンプル データを読み込み、Atlas Search インデックスを作成し、Search Tester と Data Explorer を使用してサンプル クエリを実行する方法を説明します。
所要時間: 10 分
次のビデオでは、Atlas Searchインデックスを構成し、アプリケーションからクエリを実行する方法について説明します。
所要時間: 7 分
次のビデオ チュートリアルでは、Restaurant Finder デモアプリケーション用の Atlas Search クエリを作成する方法について紹介します。このアプリケーションは www.atlassearchrestaurants.com でも入手できます。
所要時間: 20 分