Docs Menu
Docs Home
/
MongoDB Atlas
/ / / /

オートコンプリート

項目一覧

  • 定義
  • ユースケース例
  • 構文
  • オプション
  • スコアリングの動作
  • インデックスの定義
  • 基本的な例
  • あいまいな例
  • トークン注文の例
  • 例から始める
  • 簡単な any
  • 簡単な sequential
  • 強調表示の例
  • 複数のフィールドにわたる検索
  • ファセット クエリによるバケット結果
autocomplete

autocomplete演算子は、不完全な入力 string からの文字シーケンスを含む単語またはフレーズを検索します。 autocomplete演算子を使用してクエリするフィールドは、コレクションのインデックス定義の オートコンプリートデータ 型でインデックス化する必要があります。 オートコンプリート用にインデックスを構成する方法については、「 オートコンプリート用にフィールドをインデックスする方法 」を参照してください。

注意

Atlas Searchでは、 1 つのstringに 3 単語を超えるクエリに対して不正確な結果が返されることがあります。

入力しながら検索するアプリケーションで autocomplete 演算子を使用すると、アプリケーションの検索フィールドに文字が入力されるにつれて、単語を予測する精度が向上します。autocomplete は、オートコンプリート用のインデックス定義で指定されたトークン化戦略に基づいて、予測された単語を含む結果を返します。

Atlas Search autocomplete演算子を使用して推奨候補やドロップダウンを作成する場合は、推奨される検索タームのコレクションをクエリするか、過去の検索タームを使用してドロップダウンに入力することをお勧めします。 推奨される検索タームのコレクションを別途作成すると、 Atlas Search インデックスで同義語マッピングを定義して、コレクション内で正確な単語または代替単語を検索できます。 検索タームを追跡し、検索タームのメトリクスを表示してコレクションを構築できます。

autocomplete の構文は次のとおりです。

1{
2 $search: {
3 "index": "<index name>", // optional, defaults to "default"
4 "autocomplete": {
5 "query": "<search-string>",
6 "path": "<field-to-search>",
7 "tokenOrder": "any|sequential",
8 "fuzzy": <options>,
9 "score": <options>
10 }
11 }
12}
フィールド
タイプ
説明
必要性
default

query

文字列または複数の文字列の配列

検索する文字列または複数の文字列。文字列に複数のタームがある場合、Atlas Search は文字列内の各タームの一致も個別に検索します。

はい

path

string

検索するインデックス付きフィールド。 このフィールドは、 autocompleteデータ型としてインデックス付けする必要があります。 詳細については、「オートコンプリート用にフィールドをインデックスする方法 」を参照してください。

autocomplete演算子は、 pathパラメータのmultiまたはwildcard (*)オプションをサポートしていません。 また、フィールドの配列をpath値としてサポートしていません。 詳しくは、「クエリ パスを構築する 」を参照してください。

autocomplete複数のフィールドにわたる 演算子クエリの例については、「 複数のフィールドにわたる検索 」または「 Atlas Search で オートコンプリート を使用する方法の高度な例」を参照してください。

はい

fuzzy

オブジェクト

ファジー検索を有効にします。検索タームやタームに類似した文字列を検索します。

no

fuzzy
.maxEdits

integer

指定した検索タームに一致するために必要となる 1 文字の編集の最大数。値は 1 または 2 になります。

no

2

fuzzy
.prefixLength

integer

結果内の各タームの先頭にあり、完全に一致する必要がある文字数。

no

0

fuzzy
.maxExpansions

integer

生成および検索するバリエーションの最大数。この制限はトークンごとに適用されます。

no

50

score

オブジェクト

一致する検索タームの結果に割り当てるスコア。デフォルトのスコアを変更するには、次のいずれかのオプションを使用します。

boost

結果のスコアに指定された数値を掛けます。

constant

結果のスコアを指定された数値に置き換えます。

function

結果のスコアを指定された式で置き換えます。

autocomplete より高速なクエリの実行と引き換えに、 スコア の忠実度が低くなります。詳しくは、「 スコアリング動作 」を参照してください。

クエリで score を使用する方法については、「結果内のドキュメントのスコアリング」を参照してください。

no

tokenOrder

string

トークンを検索する順序。値は次のいずれかになります。

any

クエリ内のトークンがドキュメント内で任意の順序で表示できることを示します。結果には、トークンが連続して表示されるドキュメントと非連続的に表示されるドキュメントが含まれます。ただし、トークンが連続して表示される結果は、連続していない他の値よりもスコアが高くなります。

sequential

クエリ内のトークンが互いに隣接して表示されるか、ドキュメント内のクエリで指定された順序で表示される必要があることを示します。結果には、トークンが連続して表示されるドキュメントのみが含まれます。

no

any

完全一致の autocomplete 演算子クエリ結果には、完全一致でない結果よりも低いスコアが与えられます。オートコンプリート インデックスの付いたトークンの部分文字列のみを指定した場合、Atlas Search はクエリ文字列 がインデックス付きテキストと完全に一致するかどうかを判断できません。完全一致のスコアを高くするには、以下の回避策を試します。

注意

次の回避策は、すべてのケースで完全一致のスコアが高くなることを保証するものではありません。

  1. フィールドをオートコンプリート タイプと 文字列 タイプの両方としてインデックスします。

    Atlas Search autocomplete は、autocomplete フィールドも string としてインデックス付けられている場合に完全一致を優先し、スコアを増加させます。

  2. 複合演算子を使用してクエリを実行します。

この回避策を示すには、「 複数のフィールドにわたる検索 」を参照してください。

次の例では、sample_mflix データベースの movies コレクションを使用します。クラスターにサンプル データセットをロードすると、オートコンプリート用の静的インデックスを作成し、クラスターで例のクエリを実行できます。

Tip

サンプル データセットをすでに読み込んでいる場合は、「Atlas Search スタートガイド」チュートリアルに従って、インデックスの定義を作成し、Atlas Search クエリを実行します。

次のタブには、 edgeGramrightEdgeGram 、およびnGramトークン化戦略のサンプル インデックス定義が含まれています。オートコンプリート型に加えて、サンプルのインデックス定義には、title フィールドの 文字列 型と 文字列ファセット 型が含まれます。

1{
2 "mappings": {
3 "dynamic": false,
4 "fields": {
5 "title": [
6 {
7 "type": "stringFacet"
8 },
9 {
10 "type": "string"
11 },
12 {
13 "foldDiacritics": false,
14 "maxGrams": 7,
15 "minGrams": 3,
16 "tokenization": "edgeGram",
17 "type": "autocomplete"
18 }
19 ]
20 }
21 }
22}
1{
2 "mappings": {
3 "dynamic": false,
4 "fields": {
5 "title": [
6 {
7 "type": "stringFacet"
8 },
9 {
10 "type": "string"
11 },
12 {
13 "type": "autocomplete",
14 "tokenization": "rightEdgeGram",
15 "minGrams": 3,
16 "maxGrams": 7,
17 "foldDiacritics": false
18 }
19 ]
20 }
21 }
22}
1{
2 "mappings": {
3 "dynamic": false,
4 "fields": {
5 "title": [
6 {
7 "type": "stringFacet"
8 },
9 {
10 "type": "string"
11 },
12 {
13 "type": "autocomplete",
14 "tokenization": "nGram",
15 "minGrams": 3,
16 "maxGrams": 7,
17 "foldDiacritics": false
18 }
19 ]
20 }
21 }
22}

➤ [言語の選択] ドロップダウン メニューを使用して、このページの例の言語を設定します。


Search Testerのクエリ構文を表示および編集するには、以下の手順を行ってください。

1
  1. まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー

  2. まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。

  3. まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。

    [ Clusters (クラスター) ] ページが表示されます。

2

GoAtlas Searchページには、サイドバー、Data Explorer 、またはクラスターの詳細ページから できます。

  1. サイドバーで、 Services見出しの下のAtlas Searchをクリックします。

  2. [ Select data sourceドロップダウンからクラスターを選択し、[ Go to Atlas Search ] をクリックします。

    Atlas Searchページが表示されます。

  1. クラスターの [Browse Collections] ボタンをクリックします。

  2. データベースを展開し、コレクションを選択します。

  3. コレクションのSearch Indexesタブをクリックします。

    Atlas Searchページが表示されます。

  1. クラスタの名前をクリックします。

  2. [Atlas Search] タブをクリックします。

    Atlas Searchページが表示されます。

3
  1. クエリするインデックスの右側にある [ Query ] ボタンをクリックします。

  2. Edit Queryをクリックすると、 JSON形式のデフォルトのクエリ構文サンプルが表示されます。

sample_mflix データベースを使用するには、mongosh プロンプトで次のコマンドを実行します。

use sample_mflix

次のクエリは、title フィールドに off の文字が含まれる映画を検索します。

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

[
{
$search: {
autocomplete: {
path: "title",
query: "off"
}
}
}
]

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

db.movies.aggregate([
{
$search: {
"autocomplete": {
"path": "title",
"query": "off"
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1
}
}
])

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

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

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

$search

{
"autocomplete": {
"query": "off",
"path": "title"
}
}

$limit

10

$project

{
"_id": 0,
"title": 1,
}

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class AutocompleteBasicExample
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "off"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(10)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "off"}, {"path", "title"}}}}}}
limitStage := bson.D{{"$limit", 10}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class AutocompleteBasicExample {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("$search", new Document("autocomplete", new Document("query", "off").append("path", "title")));
// run pipeline and print results
collection.aggregate(Arrays.asList(agg,
limit(10),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document(
"\$search",
Document("autocomplete", Document("query", "off")
.append("path", "title"))
)
val resultsFlow = collection.aggregate<Document>(
listOf(
agg,
limit(10),
project(fields(excludeId(), include("title")))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {autocomplete: {query: "off", path: "title"}}},
{$limit: 10},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);

クエリには以下が含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"autocomplete": {"query": "off", "path": "title"}}},
{"$limit": 10},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)

注意

結果は異なる場合があります

Atlas Search は、オートコンプリート タイプのインデックス定義で構成されたトークン化戦略に応じて異なる結果を返します。詳細については、「オートコンプリートのためのフィールドのインデックス作成方法 」を参照してください。

SCORE: 9.361787796020508 _id: "573a13b0f29313caabd355c8"
countries: Array
genres: Array
runtime: 100
...
title: "Off Beat"
SCORE: 9.068204879760742 _id: "573a13aaf29313caabd22a8c"
fullplot: "An 11-year-old girl watches her father come down with a crippling depr…"
imdb: Object
year: 2003
...
title: "Off the Map"
SCORE: 9.068204879760742 _id: "573a13bef29313caabd5d208"
plot: "With white Jewish lesbians for parents and two adopted brothers - one …"
genres: Array
runtime: 76
...
title: "Off and Running"
SCORE: 8.742463111877441 _id: "573a13bbf29313caabd5567"
countries: Array
genres: Array
runtime: 98
...
title: "Hands off Mississippi"
SCORE: 8.61273193359375 _id: "5573a1396f29313caabce4791"
plot: "Unable to deal with her parents, Jeannie Tyne runs away from home. Lar…"
genres: Array
runtime: 93
...
title: "Taking Off"
SCORE: 8.61273193359375 _id: "573a1399f29313caabced3c1"
plot: "A travelling theater group find so much action going on behind-the-sce…"
genres: Array
runtime: 101
...
title: "Noises Off..."
SCORE: 8.61273193359375 _id: "573a139af29313caabcefc73"
fullplot: "In existence for a hundred years, Grimley Colliery Brass band is as ol…"
imdb: Object
year: 1996
...
title: "Brassed Off"
SCORE: 8.61273193359375 _id: "573a139af29313caabcf08f5"
fullplot: "Sean Archer, a very tough, rugged FBI Agent. Who is still grieving for…"
imdb: Object
year: 1997
...
title: "Face/Off"
SCORE: 8.603004455566406 _id: "573a13a9f29313caabd1ea36"
fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…"
imdb: Object
year: 2004
...
title: "Benji: Off the Leash!"
SCORE: 7.953945159912109 _id: "573a139af29313caabcf037c"
plot: "Desperation drives four inner-city women (Queen Latifah, Jada Pinkett …"
genres: Array
runtime: 123
...
title: "Set it Off"
SCORE: 9.81808090209961 _id: "5573a1396f29313caabce4791"
plot: "Unable to deal with her parents, Jeannie Tyne runs away from home. Lar…"
genres: Array
runtime: 93
...
title: "Taking Off"
SCORE: 9.81808090209961 _id: "573a1399f29313caabced3c1"
plot: "A travelling theater group find so much action going on behind-the-sce…"
genres: Array
runtime: 101
...
title: "Noises Off..."
SCORE: 9.81808090209961 _id: "573a139af29313caabcefc73"
fullplot: "In existence for a hundred years, Grimley Colliery Brass band is as ol…"
imdb: Object
year: 1996
...
title: "Brassed Off"
SCORE: 9.81808090209961 _id: "573a139af29313caabcf08f5"
fullplot: "Sean Archer, a very tough, rugged FBI Agent. Who is still grieving for…"
imdb: Object
year: 1997
...
title: "Face/Off"
SCORE: 9.544584274291992 _id: "573a139af29313caabcf037c"
plot: "Desperation drives four inner-city women (Queen Latifah, Jada Pinkett …"
genres: Array
runtime: 123
...
title: "Set it Off"
SCORE: 9.191947937011719 _id: "573a13bbf29313caabd5567"
countries: Array
genres: Array
runtime: 98
...
title: "Hands off Mississippi"
SCORE: 9.074413299560547 _id: "573a1398f29313caabce9f28"
plot: "A high school wise guy is determined to have a day off from school, de…"
genres: Array
runtime: 103
...
title: "Ferris Bueller's Day Off"
SCORE: 9.007184982299805 _id: "573a13b0f29313caabd355c8"
countries: Array
genres: Array
runtime: 100
...
title: "Off Beat"
SCORE: 8.700296401977539 _id: "573a13a9f29313caabd1ea36"
fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…"
imdb: Object
year: 2004
...
title: "Benji: Off the Leash!"
SCORE: 8.33833122253418 _id: "573a13aaf29313caabd22a8c"
fullplot: "An 11-year-old girl watches her father come down with a crippling depr…"
imdb: Object
year: 2003
...
title: "Off the Map"
SCORE: 5.802560806274414 _id: “573a1396f29313caabce47f4”
countries: Array
genres: Array
runtime: 98
...
title: "Come Have Coffee with Us"
SCORE: 5.790548801422119 _id: "573a13d1f29313caabd90811"
plot: "From pagan re-enactors to failed communes, black metal festivals to Ar…"
genres: Array
runtime: 98
...
title: "A Spell to Ward Off the Darkness"
SCORE: 5.7726240158081055 _id: "573a13f3f29313caabddeb07"
plot: "Turkey in the 1960s and 70s was one of the biggest producers of film i…"
genres: Array
runtime: 96
...
title: "Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema"
SCORE: 5.749281883239746 _id: "573a13a9f29313caabd1ea36"
fullplot: "Three unlikely, unsuspecting souls who come face-to-face with that mom…"
imdb: Object
year: 2004
...
title: "Benji: Off the Leash!"
SCORE: 5.749281883239746 _id: "573a13d4f29313caabd98488"
fullplot: "This tragicomedy is a self-ironic portrait of a young man who drops ou…"
imdb: Object
year: 2012
...
title: "A Coffee in Berlin"
SCORE: 5.74220085144043 _id: “573a1397f29313caabce863f”
fullplot: "Zack Mayo is a young man who has signed up for Navy Aviation Officer C…"
imdb: Object
year: 1982
...
title: "An Officer and a Gentleman"
SCORE: 5.671174049377441 _id: “573a1398f29313caabce987c”
plot: "After the end of the Dirty War, a high school teacher sets out to find…"
genres: Array
runtime: 112
...
title: "The Official Story"
SCORE: 5.671174049377441 _id: “573a13a5f29313caabd14c36”
plot: "The first days of WWI. Adrien, a young and handsome lieutenant, is wou…"
genres: Array
runtime: 135
...
title: "The Officer's Ward"
SCORE: 5.671174049377441 _id: "573a13bbf29313caabd5567"
countries: Array
genres: Array
runtime: 98
...
title: "Hands off Mississippi"
SCORE: 5.534632682800293 _id: "573a1395f29313caabce18c9"
plot: "In this "Romeo and Juliet" inspired Cold War satire starring, written …"
genres: Array
runtime: 103
...
title: "Romanoff and Juliet"

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

1{ title: 'Off Beat' },
2{ title: 'Off the Map' },
3{ title: 'Off and Running' },
4{ title: 'Hands off Mississippi' },
5{ title: 'Taking Off' },
6{ title: 'Noises Off...' },
7{ title: 'Brassed Off' },
8{ title: 'Face/Off' },
9{ title: 'Benji: Off the Leash!' },
10{ title: 'Set It Off' }

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1{ title: 'Taking Off' }
2{ title: 'Noises Off...' }
3{ title: 'Brassed Off' }
4{ title: 'Face/Off' }
5{ title: 'Set It Off' }
6{ title: 'Hands off Mississippi' }
7{ title: "Ferris Bueller's Day Off" }
8{ title: 'Off Beat' }
9{ title: 'Benji: Off the Leash!' }
10{ title: 'Off the Map' }

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1{ title: 'Come Have Coffee with Us' },
2{ title: 'A Spell to Ward Off the Darkness' },
3{ title: 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema' },
4{ title: 'Benji: Off the Leash!' },
5{ title: 'A Coffee in Berlin' },
6{ title: 'An Officer and a Gentleman' },
7{ title: 'The Official Story' },
8{ title: "The Officer's Ward" },
9{ title: 'Hands off Mississippi' },
10{ title: 'Romanoff and Juliet' }

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1{ title: 'Off Beat' },
2{ title: 'Off the Map' },
3{ title: 'Off and Running' },
4{ title: 'Hands off Mississippi' },
5{ title: 'Taking Off' },
6{ title: 'Noises Off...' },
7{ title: 'Brassed Off' },
8{ title: 'Face/Off' },
9{ title: 'Benji: Off the Leash!' },
10{ title: 'Set It Off' }

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1{ title: 'Taking Off' }
2{ title: 'Noises Off...' }
3{ title: 'Brassed Off' }
4{ title: 'Face/Off' }
5{ title: 'Set It Off' }
6{ title: 'Hands off Mississippi' }
7{ title: "Ferris Bueller's Day Off" }
8{ title: 'Off Beat' }
9{ title: 'Benji: Off the Leash!' }
10{ title: 'Off the Map' }

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1{ title: 'Come Have Coffee with Us' },
2{ title: 'A Spell to Ward Off the Darkness' },
3{ title: 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema' },
4{ title: 'Benji: Off the Leash!' },
5{ title: 'A Coffee in Berlin' },
6{ title: 'An Officer and a Gentleman' },
7{ title: 'The Official Story' },
8{ title: "The Officer's Ward" },
9{ title: 'Hands off Mississippi' },
10{ title: 'Romanoff and Juliet' }

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1{ "title": "Off Beat" }
2{ "title": "Off the Map" }
3{ "title": "Off and Running" }
4{ "title": "Hands off Mississippi" }
5{ "title": "Taking Off" }
6{ "title": "Noises Off..." }
7{ "title": "Brassed Off" }
8{ "title": "Face/Off" }
9{ "title": "Benji: Off the Leash!" }
10{ "title": "Set It Off" }

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1{ "title" : "Taking Off" }
2{ "title" : "Noises Off..." }
3{ "title" : "Brassed Off" }
4{ "title" : "Face/Off" }
5{ "title" : "Set It Off" }
6{ "title" : "Hands off Mississippi" }
7{ "title" : "Ferris Bueller's Day Off" }
8{ "title" : "Off Beat" }
9{ "title" : "Benji: Off the Leash!" }
10{ "title" : "Off the Map" }

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1{ "title" : "Come Have Coffee with Us" }
2{ "title" : "A Spell to Ward Off the Darkness" }
3{ "title" : "Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema" }
4{ "title" : "Benji: Off the Leash!" }
5{ "title" : "A Coffee in Berlin" }
6{ "title" : "An Officer and a Gentleman" }
7{ "title" : "The Official Story" }
8{ "title" : "The Officer's Ward" }
9{ "title" : "Hands off Mississippi" }
10{ "title" : "Romanoff and Juliet" }

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1[{title Off Beat}]
2[{title Off the Map}]
3[{title Off and Running}]
4[{title Hands off Mississippi}]
5[{title Taking Off}]
6[{title Noises Off...}]
7[{title Brassed Off}]
8[{title Face/Off}]
9[{title Benji: Off the Leash!}]
10[{title Set It Off}]

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1[{title Taking Off}]
2[{title Noises Off...}]
3[{title Brassed Off}]
4[{title Face/Off}]
5[{title Set It Off}]
6[{title Hands off Mississippi}]
7[{title Ferris Bueller's Day Off}]
8[{title Off Beat}]
9[{title Benji: Off the Leash!}]
10[{title Off the Map}]

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1[{title Come Have Coffee with Us}]
2[{title A Spell to Ward Off the Darkness}]
3[{title Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema}]
4[{title Benji: Off the Leash!}]
5[{title A Coffee in Berlin}]
6[{title An Officer and a Gentleman}]
7[{title The Official Story}]
8[{title The Officer's Ward}]
9[{title Hands off Mississippi}]
10[{title Romanoff and Juliet}]

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1{"title": "Off Beat"}
2{"title": "Off the Map"}
3{"title": "Off and Running"}
4{"title": "Hands off Mississippi"}
5{"title": "Taking Off"}
6{"title": "Noises Off..."}
7{"title": "Brassed Off"}
8{"title": "Face/Off"}
9{"title": "Benji: Off the Leash!"}
10{"title": "Set It Off"}

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1{"title": "Taking Off"}
2{"title": "Noises Off..."}
3{"title": "Brassed Off"}
4{"title": "Face/Off"}
5{"title": "Set It Off"}
6{"title": "Hands off Mississippi"}
7{"title": "Ferris Bueller's Day Off"}
8{"title": "Off Beat"}
9{"title": "Benji: Off the Leash!"}
10{"title": "Off the Map"}

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1{"title": "Come Have Coffee with Us"}
2{"title": "A Spell to Ward Off the Darkness"}
3{"title": "Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema"}
4{"title": "Benji: Off the Leash!"}
5{"title": "A Coffee in Berlin"}
6{"title": "An Officer and a Gentleman"}
7{"title": "The Official Story"}
8{"title": "The Officer's Ward"}
9{"title": "Hands off Mississippi"}
10{"title": "Romanoff and Juliet"}

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1Document{{title=Off Beat}}
2Document{{title=Off the Map}}
3Document{{title=Off and Running}}
4Document{{title=Hands off Mississippi}}
5Document{{title=Taking Off}}
6Document{{title=Face/Off}}
7Document{{title=Noises Off...}}
8Document{{title=Brassed Off}}
9Document{{title=Benji: Off the Leash!}}
10Document{{title=Set It Off}}

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1Document{{title=Noises Off...}}
2Document{{title=Taking Off}}
3Document{{title=Brassed Off}}
4Document{{title=Face/Off}}
5Document{{title=Set It Off}}
6Document{{title=Hands off Mississippi}}
7Document{{title=Ferris Bueller's Day Off}}
8Document{{title=Off Beat}}
9Document{{title=Benji: Off the Leash!}}
10Document{{title=Off and Running}}

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1Document{{title=Taking Off}}
2Document{{title=Noises Off...}}
3Document{{title=Brassed Off}}
4Document{{title=Face/Off}}
5Document{{title=Off Beat}}
6Document{{title=Hands off Mississippi}}
7Document{{title=Off the Map}}
8Document{{title=Set It Off}}
9Document{{title=Off and Running}}
10Document{{title=Benji: Off the Leash!}}

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1{ title: 'Off Beat' }
2{ title: 'Off the Map' }
3{ title: 'Off and Running' }
4{ title: 'Hands off Mississippi' }
5{ title: 'Taking Off' }
6{ title: 'Noises Off...' }
7{ title: 'Brassed Off' }
8{ title: 'Face/Off' }
9{ title: 'Benji: Off the Leash!' }
10{ title: 'Set It Off' }

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1{ title: 'Taking Off' }
2{ title: 'Noises Off...' }
3{ title: 'Brassed Off' }
4{ title: 'Face/Off' }
5{ title: 'Set It Off' }
6{ title: 'Hands off Mississippi' }
7{ title: "Ferris Bueller's Day Off" }
8{ title: 'Off Beat' }
9{ title: 'Benji: Off the Leash!' }
10{ title: 'Off the Map' }

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1{ title: 'Come Have Coffee with Us' }
2{ title: 'A Spell to Ward Off the Darkness' }
3{ title: 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema' }
4{ title: 'Benji: Off the Leash!' }
5{ title: 'A Coffee in Berlin' }
6{ title: 'An Officer and a Gentleman' }
7{ title: 'The Official Story' }
8{ title: "The Officer's Ward" }
9{ title: 'Hands off Mississippi' }
10{ title: 'Romanoff and Juliet' }

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

1{'title': 'Off Beat'}
2{'title': 'Off the Map'}
3{'title': 'Off and Running'}
4{'title': 'Hands off Mississippi'}
5{'title': 'Taking Off'}
6{'title': 'Noises Off...'}
7{'title': 'Brassed Off'}
8{'title': 'Face/Off'}
9{'title': 'Benji: Off the Leash!'}
10{'title': 'Set It Off'}

上記の結果では、すべてのタイトルの単語の左側に文字offが表示されます。

1{'title': 'Taking Off'}
2{'title': 'Noises Off...'}
3{'title': 'Brassed Off'}
4{'title': 'Face/Off'}
5{'title': 'Set It Off'}
6{'title': 'Hands off Mississippi'}
7{'title': "Ferris Bueller's Day Off"}
8{'title': 'Off Beat'}
9{'title': 'Benji: Off the Leash!'}
10{'title': 'Off the Map'}

上記の結果では、すべてのタイトルの単語の右側に文字offが表示されます。

1{'title': 'Come Have Coffee with Us'}
2{'title': 'A Spell to Ward Off the Darkness'}
3{'title': 'Remake, Remix, Rip-Off: About Copy Culture & Turkish Pop Cinema'}
4{'title': 'Benji: Off the Leash!'}
5{'title': 'A Coffee in Berlin'}
6{'title': 'An Officer and a Gentleman'}
7{'title': 'The Official Story'}
8{'title': "The Officer's Ward"}
9{'title': 'Hands off Mississippi'}
10{'title': 'Romanoff and Juliet'}

上記の結果では、文字offがタイトル内の異なる位置に表示されます。

次のクエリは、title フィールドに pre の文字が含まれる映画を検索します。クエリでは以下を使用します。

フィールド

説明

maxEdits

クエリをドキュメント内の単語に一致させるには、クエリ文字列の pre に 1 文字のバリエーションしかないことを示します。

prefixLength

クエリをドキュメント内の単語と照合しても、クエリ文字列の pre の最初の文字が変更できないことを示します。

maxExpansions

クエリ文字列をドキュメント内の単語と照合する場合に、pre の類似語が最大 256 個考慮されることを示します。

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

[
{
$search: {
autocomplete: {
path: "title",
query: "pre",
fuzzy: {
maxEdits: 1,
prefixLength: 1,
maxExpansions: 256
}
}
}
}
]
db.movies.aggregate([
{
$search: {
"autocomplete": {
"path": "title",
"query": "pre",
"fuzzy": {
"maxEdits": 1,
"prefixLength": 1,
"maxExpansions": 256
}
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1
}
}
])

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

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

$search

{
"autocomplete": {
"query": "pre",
"path": "title",
"fuzzy": {
"maxEdits": 1,
"prefixLength": 1,
"maxExpansions": 256
}
}
}

$limit

10

$project

{
"_id": 0,
"title": 1,
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class AutocompleteFuzzyExample
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define fuzzy options
SearchFuzzyOptions fuzzyOptions = new SearchFuzzyOptions()
{
MaxEdits = 1,
PrefixLength = 1,
MaxExpansions = 256
};
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "pre", fuzzy: fuzzyOptions))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(10)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "pre"}, {"path", "title"}, {"fuzzy", bson.D{{"maxEdits", 1},{"prefixLength", 1},{"maxExpansions", 256}}}}}}}}
limitStage := bson.D{{"$limit", 10}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class AutocompleteFuzzyExample {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("$search", new Document("autocomplete",
new Document("query", "pre")
.append("path", "title")
.append("fuzzy", new Document("maxEdits", 1).append("prefixLength", 1).append("maxExpansions", 256))));
// run pipeline and print results
collection.aggregate(Arrays.asList(agg,
limit(10),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document(
"\$search",
Document("autocomplete", Document("query", "pre")
.append("path", "title")
.append("fuzzy", Document("maxEdits", 1)
.append("prefixLength", 1)
.append("maxExpansions", 256))
)
)
val resultsFlow = collection.aggregate<Document>(
listOf(
agg,
limit(10),
project(fields(excludeId(), include("title")))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}
const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {autocomplete: {query: "pre", path: "title", fuzzy: {"maxEdits": 1, "prefixLength": 1, "maxExpansions": 256}}}},
{$limit: 10},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);
import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"autocomplete": {"query": "pre", "path": "title", "fuzzy": {"maxEdits": 1, "prefixLength": 1, "maxExpansions": 256}}}},
{"$limit": 10},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)

注意

結果は異なる場合があります

Atlas Search は、オートコンプリート タイプのインデックス定義で構成されたトークン化戦略に応じて異なる結果を返します。詳細については、「オートコンプリートのためのフィールドのインデックス作成方法 」を参照してください。

SCORE: 1 _id: “573a1390f29313caabcd5293”
plot: "Young Pauline is left a lot of money when her wealthy uncle dies. Howe…"
genres: Array
runtime: 199
...
title: "The Perils of Pauline"
SCORE: 1 _id: “573a1391f29313caabcd9458”
plot: "A young artist draws a face at a canvas on his easel. Suddenly the mou…"
genres: Array
rated: "UNRATED"
...
title: "The Blood of a Poet"
SCORE: 1 _id: “573a1392f29313caabcda09b”
plot: "Tells how King Henry VIII came to marry five more times after his divo…"
genres: Array
runtime: 97
...
title: "The Private Life of Henry VIII."
SCORE: 1 _id: “573a1392f29313caabcda556”
plot: "What do women want? Don Juan is aging. He's arrived secretly in Sevill…"
genres: Array
runtime: 89
...
title: "The Private Life of Don Juan"
SCORE: 1 _id: “573a1392f29313caabcdaee0”
plot: "The story of Dr. Samuel Mudd, who was imprisoned after innocently trea…"
genres: Array
runtime: 96
...
title: "The Prisoner of Shark Island"
SCORE: 1 _id: “573a1392f29313caabcdb3f2”
plot: "Two lookalike boys, one a poor street kid and the other a prince, exch…"
genres: Array
runtime: 118
...
title: "The Prince and the Pauper"
SCORE: 1 _id: “573a1392f29313caabcdb3f4”
plot: "An Englishman on a Ruritarian holiday must impersonate the king when t…"
genres: Array
runtime: 101
...
title: "The Prisoner of Zenda"
SCORE: 1 _id: “573a1392f29313caabcdb505”
plot: "After the death of her husband, Christine realizes she has possibly wa…"
genres: Array
runtime: 144
...
title: "Dance Program"
SCORE: 1 _id: “573a1393f29313caabcdca58”
plot: "While traveling in France during the Nazi invasion of 1940, an English…"
genres: Array
runtime: 87
...
title: "The Pied Piper"
SCORE: 1 _id: “573a1393f29313caabcdca76”
plot: "The official World War II US Government film statement defining the va…"
genres: Array
runtime: 87
...
title: "Prelude to War"
SCORE: 1 _id: “573a1390f29313caabcd5ea4”
plot: "A District Attorney's outspoken stand on abortion gets him in trouble …"
genres: Array
runtime: 62
...
title: "Where Are My Children?"
SCORE: 1 _id: “573a1391f29313caabcd70b4”
plot: "An extended family split up in France and Germany find themselves on o…"
genres: Array
runtime: 150
...
title: "The Four Horsemen of the Apocalypse"
SCORE: 1 _id: “573a1391f29313caabcd7850”
plot: "In fifteenth century Paris, the brother of the archdeacon plots with t…"
genres: Array
runtime: 133
...
title: "The Hunchback of Notre Dame"
SCORE: 1 _id: “573a1391f29313caabcd8cbd”
plot: "A young lady from Georgia goes to Hollywood in the hopes of becoming a…"
genres: Array
runtime: 83
...
title: "Show People"
SCORE: 1 _id: “573a1392f29313caabcd9df7”
plot: "A young American man is transported back to London in the time of the …"
genres: Array
runtime: 84
...
title: "Berkeley Square"
SCORE: 1 _id: “573a1392f29313caabcda7fb”
plot: "An entertainer impersonates a look-alike banker, causing comic confusi…"
genres: Array
runtime: 82
...
title: "Folies Bergère de Paris"
SCORE: 1 _id: “573a1393f29313caabcdc4a2”
plot: "Boxer Joe Pendleton dies 50 years too soon due to a heavenly mistake, …"
genres: Array
runtime: 94
...
title: "Here Comes Mr. Jordan"
SCORE: 1 _id: “573a1393f29313caabcdc814”
plot: "An American man marries a Serbian immigrant who fears that she will tu…"
genres: Array
runtime: 73
...
title: "Cat People"
SCORE: 1 _id: “573a1393f29313caabcdc87b”
plot: "Mail author for translation. Kodos hegycsucsok, fekete fenyvesek vilag…"
genres: Array
runtime: 88
...
title: "People on the Alps"
SCORE: 1 _id: “573a1393f29313caabcdcd39”
plot: "A soldier falls for a chorus girl and then experiences trouble when he…"
genres: Array
runtime: 103
...
title: "The Gang's All Here"
SCORE: 1 _id: “573a1390f29313caabcd5293”
plot: "Young Pauline is left a lot of money when her wealthy uncle dies. Howe…"
genres: Array
runtime: 199
...
title: "The Perils of Pauline"
SCORE: 1 _id: “573a1390f29313caabcd5967”
plot: "An intrepid reporter and his loyal friend battle a bizarre secret soci…"
genres: Array
runtime: 399
...
title: "Les vampires"
SCORE: 1 _id: “573a1391f29313caabcd6ea2”
plot: "The simple-minded son of a rich financier must find his own way in the…"
genres: Array
runtime: 77
...
title: "The Saphead"
SCORE: 1 _id: “573a1391f29313caabcd70b4”
plot: "An extended family split up in France and Germany find themselves on o…"
genres: Array
runtime: 150
...
title: "The Four Horsemen of the Apocalypse"
SCORE: 1 _id: “573a1391f29313caabcd7b98”
plot: "A bitter clown endeavors to rescue the young woman he loves from the l…"
genres: Array
runtime: 95
...
title: "He Who Gets Slapped"
SCORE: 1 _id: “573a1391f29313caabcd806b”
plot: "A mad, disfigured composer seeks love with a lovely young opera singer…"
genres: Array
runtime: 93
...
title: "The Phantom of the Opera"
SCORE: 1 _id: “573a1391f29313caabcd8cbd”
plot: "A young lady from Georgia goes to Hollywood in the hopes of becoming a…"
genres: Array
runtime: 83
...
title: "Show People"
SCORE: 1 _id: “573a1391f29313caabcd9458”
plot: "A young artist draws a face at a canvas on his easel. Suddenly the mou…"
genres: Array
rated: "UNRATED"
...
title: "The Blood of a Poet"
SCORE: 1 _id: “573a1391f29313caabcd9651”
plot: "In London at the turn of the century, the bandit Mack the Knife marrie…"
genres: Array
runtime: 112
...
title: "The 3 Penny Opera"
SCORE: 1 _id: “573a1392f29313caabcd9caa”
plot: "Many passengers on the Shanghai Express are more concerned that the no…"
genres: Array
runtime: 82
...
title: "Shanghai Express"

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

1{ title: 'The Perils of Pauline' },
2{ title: 'The Blood of a Poet' },
3{ title: 'The Private Life of Henry VIII.' },
4{ title: 'The Private Life of Don Juan' },
5{ title: 'The Prisoner of Shark Island' },
6{ title: 'The Prince and the Pauper' },
7{ title: 'The Prisoner of Zenda' },
8{ title: 'Dance Program' },
9{ title: 'The Pied Piper' },
10{ title: 'Prelude to War' }

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1{ title: 'Where Are My Children?' }
2{ title: 'The Four Horsemen of the Apocalypse' }
3{ title: 'The Hunchback of Notre Dame' }
4{ title: 'Show People' }
5{ title: 'Berkeley Square' }
6{ title: 'Folies Bergère de Paris' }
7{ title: 'Here Comes Mr. Jordan' }
8{ title: 'Cat People' }
9{ title: 'People on the Alps' }
10{ title: "The Gang's All Here" }

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1{ title: 'The Perils of Pauline' }
2{ title: 'Les vampires' }
3{ title: 'The Saphead' }
4{ title: 'The Four Horsemen of the Apocalypse' }
5{ title: 'He Who Gets Slapped' }
6{ title: 'The Phantom of the Opera' }
7{ title: 'Show People' }
8{ title: 'The Blood of a Poet' }
9{ title: 'The 3 Penny Opera' }
10{ title: 'Shanghai Express' }

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1{ title: 'The Perils of Pauline' },
2{ title: 'The Blood of a Poet' },
3{ title: 'The Private Life of Henry VIII.' },
4{ title: 'The Private Life of Don Juan' },
5{ title: 'The Prisoner of Shark Island' },
6{ title: 'The Prince and the Pauper' },
7{ title: 'The Prisoner of Zenda' },
8{ title: 'Dance Program' },
9{ title: 'The Pied Piper' },
10{ title: 'Prelude to War' }

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1{ title: 'Where Are My Children?' }
2{ title: 'The Four Horsemen of the Apocalypse' }
3{ title: 'The Hunchback of Notre Dame' }
4{ title: 'Show People' }
5{ title: 'Berkeley Square' }
6{ title: 'Folies Bergère de Paris' }
7{ title: 'Here Comes Mr. Jordan' }
8{ title: 'Cat People' }
9{ title: 'People on the Alps' }
10{ title: "The Gang's All Here" }

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1{ title: 'The Perils of Pauline' }
2{ title: 'Les vampires' }
3{ title: 'The Saphead' }
4{ title: 'The Four Horsemen of the Apocalypse' }
5{ title: 'He Who Gets Slapped' }
6{ title: 'The Phantom of the Opera' }
7{ title: 'Show People' }
8{ title: 'The Blood of a Poet' }
9{ title: 'The 3 Penny Opera' }
10{ title: 'Shanghai Express' }

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1{ "title" : "The Perils of Pauline" }
2{ "title" : "The Blood of a Poet" }
3{ "title" : "The Private Life of Henry VIII." }
4{ "title" : "The Private Life of Don Juan" }
5{ "title" : "The Prisoner of Shark Island" }
6{ "title" : "The Prince and the Pauper" }
7{ "title" : "The Prisoner of Zenda" }
8{ "title" : "Dance Program" }
9{ "title" : "The Pied Piper" }
10{ "title" : "Prelude to War" }

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1{ "title" : "Where Are My Children?" }
2{ "title" : "The Four Horsemen of the Apocalypse" }
3{ "title" : "The Hunchback of Notre Dame" }
4{ "title" : "Show People" }
5{ "title" : "Berkeley Square" }
6{ "title" : "Folies Bergère de Paris" }
7{ "title" : "Here Comes Mr. Jordan" }
8{ "title" : "Cat People" }
9{ "title" : "People on the Alps" }
10{ "title" : "The Gang's All Here" }

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1{ "title" : "The Perils of Pauline" }
2{ "title" : "Les vampires" }
3{ "title" : "The Saphead" }
4{ "title" : "The Four Horsemen of the Apocalypse" }
5{ "title" : "He Who Gets Slapped" }
6{ "title" : "The Phantom of the Opera" }
7{ "title" : "Show People" }
8{ "title" : "The Blood of a Poet" }
9{ "title" : "The 3 Penny Opera" }
10{ "title" : "Shanghai Express" }

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1[{title The Perils of Pauline}]
2[{title The Blood of a Poet}]
3[{title The Private Life of Henry VIII.}]
4[{title The Private Life of Don Juan}]
5[{title The Prisoner of Shark Island}]
6[{title The Prince and the Pauper}]
7[{title The Prisoner of Zenda}]
8[{title Dance Program}]
9[{title The Pied Piper}]
10[{title Prelude to War}]

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1[{title Where Are My Children?}]
2[{title The Four Horsemen of the Apocalypse}]
3[{title The Hunchback of Notre Dame}]
4[{title Show People}]
5[{title Berkeley Square}]
6[{title Folies Bergère de Paris}]
7[{title Here Comes Mr. Jordan}]
8[{title Cat People}]
9[{title People on the Alps}]
10[{title The Gang's All Here}]

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1[{title The Perils of Pauline}]
2[{title Les vampires}]
3[{title The Saphead}]
4[{title The Four Horsemen of the Apocalypse}]
5[{title He Who Gets Slapped}]
6[{title The Phantom of the Opera}]
7[{title Show People}]
8[{title The Blood of a Poet}]
9[{title The 3 Penny Opera}]
10[{title Shanghai Express}]

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1{"title": "The Perils of Pauline"}
2{"title": "The Blood of a Poet"}
3{"title": "The Private Life of Henry VIII."}
4{"title": "The Private Life of Don Juan"}
5{"title": "The Prisoner of Shark Island"}
6{"title": "The Prince and the Pauper"}
7{"title": "The Prisoner of Zenda"}
8{"title": "Dance Program"}
9{"title": "The Pied Piper"}
10{'title': 'Prelude to War'}

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1{"title": "Where Are My Children?"}
2{"title": "The Four Horsemen of the Apocalypse"}
3{"title": "The Hunchback of Notre Dame"}
4{"title": "Show People"}
5{"title": "Berkeley Square"}
6{"title": "Folies Bergère de Paris"}
7{"title": "Here Comes Mr. Jordan"}
8{"title": "Cat People"}
9{"title": "People on the Alps"}
10{"title": "The Gang's All Here"}

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1{"title": "The Perils of Pauline"}
2{"title": "Les vampires"}
3{"title": "The Saphead"}
4{"title": "The Four Horsemen of the Apocalypse"}
5{"title": "He Who Gets Slapped"}
6{"title": "The Phantom of the Opera"}
7{"title": "Show People"}
8{"title": "The Blood of a Poet"}
9{"title": "The 3 Penny Opera"}
10{"title": "Shanghai Express"}

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1Document{{title=The Perils of Pauline}}
2Document{{title=The Private Life of Henry VIII.}}
3Document{{title=Prelude to War}}
4Document{{title=Sitting Pretty}}
5Document{{title=The Prisoner}}
6Document{{title=Chi lavora è perduto (In capo al mondo)}}
7Document{{title=Profound Desires of the Gods}}
8Document{{title=The Protagonists}}
9Document{{title=Property Is No Longer a Theft}}
10Document{{title=Premiya}}

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1Document{{title=The Four Horsemen of the Apocalypse}}
2Document{{title=Folies Bergère de Paris}}
3Document{{title=Mother Wore Tights}}
4Document{{title=El hombre sin rostro}}
5Document{{title=Il segno di Venere}}
6Document{{title=Creature from the Black Lagoon}}
7Document{{title=Susan Slept Here}}
8Document{{title=Tell Them Willie Boy Is Here}}
9Document{{title=Pilatus und andere - Ein Film fèr Karfreitag}}
10Document{{title=Watch Out, We're Mad}}

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1Document{{title=The Four Horsemen of the Apocalypse}}
2Document{{title=The Private Life of Henry VIII.}}
3Document{{title=David Copperfield}}
4Document{{title=The Prisoner of Zenda}}
5Document{{title=People on the Alps}}
6Document{{title=Prelude to War}}
7Document{{title=The Pride of the Yankees}}
8Document{{title=Phantom of the Opera}}
9Document{{title=The Curse of the Cat People}}
10Document{{title=The People Against O'Hara}}

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1{ title: 'The Perils of Pauline' }
2{ title: 'The Blood of a Poet' }
3{ title: 'The Private Life of Henry VIII.' }
4{ title: 'The Private Life of Don Juan' }
5{ title: 'The Prisoner of Shark Island' }
6{ title: 'The Prince and the Pauper' }
7{ title: 'The Prisoner of Zenda' }
8{ title: 'Dance Program' }
9{ title: 'The Pied Piper' }
10{ title: 'Prelude to War' }

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1{ title: 'Where Are My Children?' }
2{ title: 'The Four Horsemen of the Apocalypse' }
3{ title: 'The Hunchback of Notre Dame' }
4{ title: 'Show People' }
5{ title: 'Berkeley Square' }
6{ title: 'Folies Bergère de Paris' }
7{ title: 'Here Comes Mr. Jordan' }
8{ title: 'Cat People' }
9{ title: 'People on the Alps' }
10{ title: "The Gang's All Here" }

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1{ title: 'The Perils of Pauline' }
2{ title: 'Les vampires' }
3{ title: 'The Saphead' }
4{ title: 'The Four Horsemen of the Apocalypse' }
5{ title: 'He Who Gets Slapped' }
6{ title: 'The Phantom of the Opera' }
7{ title: 'Show People' }
8{ title: 'The Blood of a Poet' }
9{ title: 'The 3 Penny Opera' }
10{ title: 'Shanghai Express' }

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

1{'title': 'The Perils of Pauline'}
2{'title': 'The Blood of a Poet'}
3{'title': 'The Private Life of Henry VIII.'}
4{'title': 'The Private Life of Don Juan'}
5{'title': 'The Prisoner of Shark Island'}
6{'title': 'The Prince and the Pauper'}
7{'title': 'The Prisoner of Zenda'}
8{'title': 'Dance Program'}
9{'title': 'The Pied Piper'}
10{'title': 'Prelude to War'}

これらの結果は、すべてのタイトルにおいて、1文字の変更を加え、単語の左側の最初の文字を固定した状態で、クエリ文字列に対して予測される単語を示しています。

1{'title': 'Where Are My Children?'}
2{'title': 'The Four Horsemen of the Apocalypse'}
3{'title': 'The Hunchback of Notre Dame'}
4{'title': 'Show People'}
5{'title': 'Berkeley Square'}
6{'title': 'Folies Bergère de Paris'}
7{'title': 'Here Comes Mr. Jordan'}
8{'title': 'Cat People'}
9{'title': 'People on the Alps'}
10{'title': "The Gang's All Here"}

これらの結果は、すべてのタイトルで、1 文字の変更と単語の右側の最初の文字定数を使用してクエリ文字列に対して予測される単語を示しています

1{'title': 'The Perils of Pauline'}
2{'title': 'Les vampires'}
3{'title': 'The Saphead'}
4{'title': 'The Four Horsemen of the Apocalypse'}
5{'title': 'He Who Gets Slapped'}
6{'title': 'The Phantom of the Opera'}
7{'title': 'Show People'}
8{'title': 'The Blood of a Poet'}
9{'title': 'The 3 Penny Opera'}
10{'title': 'Shanghai Express'}

これらの結果は、タイトル内の単語のさまざまな位置で1文字を変更してクエリ文字列に対して予測される単語を示しています。

次のクエリは、title フィールドに men with の文字が含まれる映画を検索します。クエリでは tokenOrder フィールドも使用され、このフィールドでは、クエリがトークンを any の順序で検索するか、sequential の順序で検索するかを指定します。

キーワード アナライザーを使用してフィールドにインデックスを付けると、 titleフィールドで用語またはフレーズで始まる映画のタイトルを検索できます

次のサンプル クエリの結果を取得するには、edgeGram トークン化戦略のキーワード アナライザを使用してフィールドをインデックスする必要があります。他の組み込みアナライザを使用してフィールドをインデックスすると、Atlas Search はテキスト フィールドを単一の用語としてインデックスしないため、結果を返しません。edgeGram トークン化戦略では、単語の左側からトークンが作成されます。

大文字と小文字を区別しない結果を返すには、foldDiacriticstrue に設定する必要があります。foldDiacriticsfalse に設定した場合、Atlas Search が結果を返すには、クエリ タームの大文字と小文字がドキュメント内の大文字と小文字と完全に一致している必要があります。

{
"mappings": {
"dynamic": false,
"fields": {
"title": [
{
"type": "stringFacet"
},
{
"type": "string"
},
{
"foldDiacritics": true,
"maxGrams": 7,
"minGrams": 3,
"analyzer": "lucene.keyword",
"tokenization": "edgeGram",
"type": "autocomplete"
}]
}
}
}

次のクエリは、Fast & という単語で始まる映画タイトルを検索します。

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

[
{
$search: {
autocomplete: {
path: "title",
query: "Fast &",
tokenOrder: "sequential"
}
}
}
]

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

db.movies.aggregate([
{
$search: {
"autocomplete": {
"query": "Fast &",
"path": "title",
"tokenOrder": "sequential"
}
}
},
{
$project: {
"_id": 0,
"title": 1
}
},
{
$limit: 4
}
])

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

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

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

$search

{
"autocomplete": {
"query": "Fast &",
"path": "title",
"tokenOrder": "sequential"
}
}

$limit

4

$project

{
"_id": 0,
"title": 1,
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class AutocompleteTokenOrderSequentialStartsWithExample
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "Fast &", SearchAutocompleteTokenOrder.Sequential))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(4)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "Fast &"}, {"path", "title"}, {"tokenOrder", "sequential"}}}}}}
limitStage := bson.D{{"$limit", 4}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class AutocompleteStartsWith {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("$search", new Document("autocomplete", new Document("query", "Fast &").append("path", "title").append("tokenOrder", "sequential")));
// run pipeline and print results
collection.aggregate(Arrays.asList(agg,
limit(4),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document(
"\$search",
Document(
"autocomplete",
Document("query", "Fast &")
.append("path", "title")
.append("tokenOrder", "sequential")
)
)
val resultsFlow = collection.aggregate<Document>(
listOf(
agg,
limit(4),
project(fields(excludeId(), include("title")))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {autocomplete: {query: "Fast &", path: "title", tokenOrder: "sequential"}}},
{$limit: 4},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"autocomplete": {"query": "men with", "path": "title", "tokenOrder": "sequential"}}},
{"$limit": 4},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)
SCORE: 10.042893409729004 _id: “573a13bdf29313caabd5929f”
fullplot: "Heading back to the streets where it all began, two men rejoin two wom…"
imdb: Object
year: 2009
...
title: "Fast & Furious"
SCORE: 9.515419006347656 _id: “573a13d3f29313caabd95cc5”
fullplot: "Since Dom (Diesel) and Brian's (Walker) Rio heist toppled a kingpin's …"
imdb: Object
year: 2013
...
title "Fast & Furious 6"

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

1{ title: 'Fast & Furious' },
2{ title: 'Fast & Furious 6' }
1{ title: 'Fast & Furious' },
2{ title: 'Fast & Furious 6' }
1{ "title" : "Fast & Furious" }
2{ "title" : "Fast & Furious 6" }
1 [{title Fast & Furious}]
2 [{title Fast & Furious 6}]
1{"title": "Fast & Furious"}
2{"title": "Fast & Furious 6"}
1Document{{title=Fast & Furious}}
2Document{{title=Fast & Furious 6}}
1{ title: 'Fast & Furious' }
2{ title: 'Fast & Furious 6' }
1{'title': 'Fast & Furious'}
2{'title': 'Fast & Furious 6'}

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

[
{
$search: {
autocomplete: {
path: "title",
query: "men with",
tokenOrder: "any"
}
}
}
]

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

db.movies.aggregate([
{
$search: {
"autocomplete": {
"path": "title",
"query": "men with",
"tokenOrder": "any"
}
}
},
{
$limit: 4
},
{
$project: {
"_id": 0,
"title": 1
}
}
])

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

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

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

$search

{
"autocomplete": {
"query": "men with",
"path": "title",
"tokenOrder": "any"
}
}

$limit

4

$project

{
"_id": 0,
"title": 1,
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class AutocompleteTokenOrderAnyExample
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Autocomplete(movie => movie.Title, "men with", SearchAutocompleteTokenOrder.Any))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(4)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"autocomplete", bson.D{{"query", "men with"}, {"path", "title"}, {"tokenOrder", "any"}}}}}}
limitStage := bson.D{{"$limit", 4}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class AutocompleteTokenAny {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("$search", new Document("autocomplete", new Document("query", "men with").append("path", "title").append("tokenOrder", "any")));
// run pipeline and print results
collection.aggregate(Arrays.asList(agg,
limit(4),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}

各クエリには、次のものが含まれます。

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

  • $projectステージでは、 title以外のすべてのフィールドを除外します。

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>(