wildcard
定義
wildcard
wildcard
演算子を使用すると、検索文字列に任意の文字と一致する特殊文字を使用するクエリが可能になります。文字説明?
任意の 1 文字と一致します。
*
0 文字以上の文字と一致します。
\
エスケープ文字。
wildcard
はタームレベルの演算子であり、query
フィールドは分析されないことを意味します。query
フィールドは特殊文字を含む 1 つのタームとして扱われるため、タームレベルの演算子は キーワード アナライザと連携します。分析されたquery
フィールドと分析されていないquery
フィールドに対するクエリの例については、「分析されたフィールドの例」を参照してください。
構文
wildcard
の構文は次のとおりです。
{ $search: { "index": <index name>, // optional, defaults to "default" "wildcard": { "query": "<search-string>", "path": "<field-to-search>", "allowAnalyzedField": <boolean>, "score": <options> } } }
オプション
wildcard
では、次の用語を使用してクエリを作成します。
フィールド | タイプ | 説明 | 必要性 | default |
---|---|---|---|---|
| 文字列または複数の文字列の配列 | 検索する文字列または複数の文字列。 | はい | |
| 文字列または複数の文字列の配列 | 検索対象となるインデックス付きフィールド。ワイルドカード パスを指定して検索することもできます。 | はい | |
| ブール値 | 分析対象フィールドに対してクエリを実行する場合は、 | no |
|
| オブジェクト | 一致する検索用語の結果に割り当てられたスコアを変更します。次の選択肢があります。
クエリで | no |
動作
wildcard
はタームレベルの演算子であり、 query
フィールドは分析されないことを意味します。allowAnalyzedField
オプションを true
に設定することで、インデックス作成中に wildcard
演算子を使用して分析されたフィールドを検索することが可能です。ただし、結果はクエリ テキストが分析されていないことを示しています。
次の例は、分析済みフィールドで検索を実行する際にwildcard
演算子がどのように動作するかを示しています。
例
標準アナライザ
フィールド foo bar baz
は標準アナライザでインデックス付けされてます。Atlas Search はフィールドを分析し、foo
、 bar
、 baz
としてインデックスを作成します。このフィールドで foo bar*
を検索しても何も見つかりません。これは、ワイルドカード演算子が foo bar*
を末尾にワイルドカードが付いた単一の検索用語として扱うためです。つまり、Atlas Search はフィールド内で foo bar
で始まる用語を検索しますが、用語が存在しないため何も見つかりません。
例
キーワードアナライザ
キーワード アナライザーでインデックス付けされたフィールドで *Star Trek*
を検索すると、任意のコンテキストでフィールドに文字列 Star Trek
が含まれるすべてのドキュメントが見つかります。標準アナライザでフィールドにインデックス付けされた *Star
Trek*
を検索しても何も見つかりません。これは、 Star
とTrek
の間にスペースがあり、インデックスにスペースが含まれていないためです。
エスケープ文字の動作
mongosh
またはドライバーとともにエスケープ文字を使用する場合は、エスケープ文字の前にdoubleバックスラッシュを使用する必要があります。
例
リテラル アスタリスクを含む任意の文字列を検索するワイルドカード式を作成するには、次の式を使用します。
"*\\**"
最初と最後のアスタリスクは任意の文字に一致するワイルドカードとして機能し、\\*
はリテラルのアスタリスクに一致します。
注意
次の式を使用して、リテラルのバックスラッシュをエスケープします。
"*\\\*"
➤ [言語の選択] ドロップダウン メニューを使用して、このページの例の言語を設定します。
例
次の例では、キーワード アナライザ を使用するカスタム インデックス定義を持つ sample_mflix
データベースの movies
コレクションを使用します。クラスターに サンプル データセット がある場合は、movies
コレクションに Atlas Search インデックスを作成し、クラスターでサンプル クエリを実行できます。
Search Testerのクエリ構文を表示および編集するには、以下の手順を行ってください。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
警告
ナビゲーションの改善が進行中です。
現在、新しく改善されたナビゲーション エクスペリエンスを展開しています。次の手順が Atlas UIのビューと一致しない場合は、プレビュー ドキュメントを参照してください。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
次のクエリを Atlas UI で実行する方法については、「クエリの定義」を参照してください。
MongoDB Compass で次のクエリを実行する方法については、「クエリを定義する」を参照してください。
MongoDB C# ドライバーを使用して次のクエリを実行する方法については、「クエリの定義」を参照してください。
MongoDB Java ドライバーを使用して次の MongoDB クエリを実行する方法については、「クエリの定義」を参照してください。
MongoDB Kotlin ドライバーを使用して次のクエリを実行する方法については、「クエリの定義」を参照してください。
MongoDB Node ドライバーを使用して次のクエリを実行する方法については、「クエリの定義」を参照してください。
PyMongo ドライバーを使用して次のクエリを実行する方法については、「クエリの定義」を参照してください。
インデックスの例
次のインデックス定義は、キーワード アナライザを使用して、movies
コレクションの title
フィールドにインデックスを作成します。
1 { 2 "mappings": { 3 "fields": { 4 "title": { 5 "analyzer": "lucene.keyword", 6 "type": "string" 7 } 8 } 9 } 10 }
クエリ例
次の例では、Green D
で始まり、その後に任意の数の他の文字が続く映画のタイトルをすべての title
フィールドで検索します。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
[ { $search: { "wildcard": { "path": "title", "query": "Green D*" } } } ]
SCORE: 1 _id: "573a1393f29313caabcddaf5" plot: "Sophie loved Edmund, but he left town when her parents forced her to m…" genres: Array runtime: 141 SCORE: 1 _id: "573a13a2f29313caabd0a4e4" plot: "The story of some Vietnamese refugees as they first arrive at Camp Pen…" genres: Array runtime: 115
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
db.movies.aggregate([ { "$search": { "wildcard": { "path": "title", "query": "Green D*" } } }, { "$project": { "_id": 0, "title": 1 } } ])
{ "title" : "Green Dolphin Street" } { "title" : "Green Dragon" }
In the :guilabel:`Aggregations` tab of the ``movies`` collection, configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click :guilabel:`Add Stage` to add additional stages. .. list-table:: :header-rows: 1 :widths: 25 75 * - Pipeline Stage - Query * - ``$search`` - .. code-block:: javascript { "wildcard": { "query": "Green D*", "path": "title" } } * - ``$project`` - .. code-block:: javascript { "_id": 0, "title": 1, }
{ "title" : "Green Dolphin Street" } { "title" : "Green Dragon" }
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class WildcardSingleCharacter { 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.Wildcard(movie => movie.Title, "Green D*")) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
{ "title" : "Green Dolphin Street" } { "title" : "Green Dragon" }
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(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{{"wildcard", bson.D{{"path", "title"}, {"query", "Green D*"}}}}}} projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}} // run pipeline cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, 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) } }
[{title Green Dolphin Street}] [{title Green Dragon}]
import static com.mongodb.client.model.Filters.eq; 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 WildcardSingleCharacter { 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("query", "Green D*").append("path", "title"); // run pipeline and print results collection.aggregate(Arrays.asList( eq("$search", eq("wildcard", agg)), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
{"title": "Green Dolphin Street"} {"title": "Green Dragon"}
import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Filters.eq 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("query", "Green D*").append("path", "title") val resultsFlow = collection.aggregate<Document>( listOf( eq("\$search", eq("wildcard", agg)), project(fields( excludeId(), include("title") )) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
Document{{title=Green Dolphin Street}} Document{{title=Green Dragon}}
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: {wildcard: {query: "Green D*", path: "title"}}}, {$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);
{ title: 'Green Dolphin Street' } { title: 'Green Dragon' }
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"wildcard": {"query": "Green D*", "path": "title"}}}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
{'title': 'Green Dolphin Street'} {'title': 'Green Dragon'}
次の例では、文字列 Wom?n
(?
は任意の 1 文字)で始まり、その後にスペースが続き、任意の数の追加文字が続く映画のタイトルを、すべての title
フィールドで検索します。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
[ { $search: { "wildcard": { "path": "title", "query": "Wom?n *" } } } ]
SCORE: 1 _id: "573a1393f29313caabcdcbdd" plot: "Rival reporters Sam and Tess fall in love and get married, only to fin…" genres: Array runtime: 114 SCORE: 1 _id: "573a1394f29313caabce08c6" plot: "A married, middle-aged woman is shocked to discover that her husband, …" genres: Array runtime: 93 SCORE: 1 _id: "573a1396f29313caabce42e5" plot: "The battle of the sexes and relationships among the elite of Britian's…" genres: Array runtime: 131 SCORE: 1 _id: "573a1398f29313caabceb06d" fullplot: "A woman's lover leaves her, and she tries to contact him to find out w…" imdb: Object year: 1988 SCORE: 1 _id: "573a139df29313caabcf9c83" plot: "A new woman comes between a widower and his adult son." genres: Array runtime: 110 SCORE: 1 _id: "573a13a0f29313caabd050bf" fullplot: "Isabella is a great cook, making her husband's restaurant in Bahia, Br…" imdb: Object year: 2000 SCORE: 1 _id: "573a13aaf29313caabd22c05" countries: Array genres: Array runtime: 115 SCORE: 1 _id: "573a13aef29313caabd2d899" countries: Array genres: Array runtime: 72 SCORE: 1 _id: "573a13aff29313caabd32566" fullplot: "An adaptation of Bishop T.D. Jakes' self-help novel, chronciling a wom…" imdb: Object year: 2004 SCORE: 1 _id: "573a13b0f29313caabd332de" fullplot: "Two college friends get together and reminisce on the woman they both …" imdb: Object year: 2004
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
db.movies.aggregate([ { "$search": { "wildcard": { "path": "title", "query": "Wom?n *" } } }, { "$limit": 5 }, { "$project": { "_id": 0, "title": 1 } } ])
[ { title: 'Woman of the Year' }, { title: 'Woman in a Dressing Gown' }, { title: 'Women in Love' }, { title: 'Women on the Verge of a Nervous Breakdown' }, { title: 'Woman Wanted' } ]
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
In the :guilabel:`Aggregations` tab of the ``movies`` collection, configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click :guilabel:`Add Stage` to add additional stages. .. list-table:: :header-rows: 1 :widths: 25 75 * - Pipeline Stage - Query * - ``$search`` - .. code-block:: javascript { "wildcard": { "query": "Wom?n *", "path": "title" } } * - ``$limit`` - .. code-block:: javascript 5 * - ``$project`` - .. code-block:: javascript { "_id": 0, "title": 1, }
{ title: 'Woman of the Year' }, { title: 'Woman in a Dressing Gown' }, { title: 'Women in Love' }, { title: 'Women on the Verge of a Nervous Breakdown' }, { title: 'Woman Wanted' }
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class WildcardMultipleCharacter { 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.Wildcard(movie => movie.Title, "Wom?n *")) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(5) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
{ title: 'Woman of the Year' }, { title: 'Woman in a Dressing Gown' }, { title: 'Women in Love' }, { title: 'Women on the Verge of a Nervous Breakdown' }, { title: 'Woman Wanted' }
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(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{{"wildcard", bson.D{{"path", "title"}, {"query", "Wom?n *"}}}}}} limitStage := bson.D{{"$limit", 5}} 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
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
import static com.mongodb.client.model.Filters.eq; 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 WildcardMultiCharacter { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespsace MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // define pipeline Document agg = new Document("query", "Wom?n *").append("path", "title"); // run pipeline and print results collection.aggregate(Arrays.asList( eq("$search", eq("wildcard", agg)), limit(5), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
[{title Woman of the Year}] [{title Woman in a Dressing Gown}] [{title Women in Love}] [{title Women on the Verge of a Nervous Breakdown}] [{title Woman Wanted}]
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Filters.eq 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("query", "Wom?n *").append("path", "title") val resultsFlow = collection.aggregate<Document>( listOf( eq("\$search", eq("wildcard", agg)), limit(5), project(fields( excludeId(), include("title") )) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
{"title": "Woman of the Year"} {"title": "Woman in a Dressing Gown"} {"title": "Women in Love"} {"title": "Women on the Verge of a Nervous Breakdown"} {"title": "Woman Wanted"}
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$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: {wildcard: {query: "Wom?n *", path: "title"}}}, {$limit: 5}, {$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);
{ title: 'Woman of the Year' } { title: 'Woman in a Dressing Gown' } { title: 'Women in Love' } { title: 'Women on the Verge of a Nervous Breakdown' } { title: 'Woman Wanted' }
$limit
ステージでは、結果を 5 つのドキュメントに制限し、$project
ステージでは、結果を title
フィールドのみに制限します。
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"wildcard": {"query": "Wom?n *", "path": "title"}}}, {"$limit": 5}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
{'title': 'Woman of the Year'} {'title': 'Woman in a Dressing Gown'} {'title': 'Women in Love'} {'title': 'Women on the Verge of a Nervous Breakdown'} {'title': 'Woman Wanted'}
次の例では、エスケープ文字を使用して、title
フィールドが疑問符で終わるドキュメントを検索します。
注意
次の例は mongosh
で実行することを目的としています。ドライバーでエスケープ文字を使用する方法について詳しくは、「エスケープ文字の動作」を参照してください。
query
フィールドの *
文字は任意の文字に一致し、\\?
文字列はリテラルの疑問符に一致します。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
[ { $search: { "wildcard": { "path": "title", "query": "*\\?" } } } ]
SCORE: 1 _id: "573a1390f29313caabcd5ea4" plot: "A District Attorney's outspoken stand on abortion gets him in trouble …" genres: Array runtime: 62 SCORE: 1 _id: "573a1392f29313caabcdab4a" plot: "Robin is crooning to a Mae West-like Jenny Wren when he is shot with a…" genres: Array runtime: 8 SCORE: 1 _id: "573a1394f29313caabce08ab" plot: "Elmer Fudd is again hunting rabbits - only this time it's an opera. Wa…" genres: Array runtime: 7 SCORE: 1 _id: "573a1394f29313caabce08c8" plot: "To save his career, an ad man wants a sex symbol to endorse a lipstick…" genres: Array runtime: 93 SCORE: 1 _id: "573a1395f29313caabce1555" plot: "In order to get back into the good graces with his wife with whom he h…" genres: Array runtime: 115 SCORE: 1 _id: "573a1395f29313caabce1dce" plot: "A former child star torments her crippled sister in a decaying Hollywo…" genres: Array runtime: 134 SCORE: 1 _id: "573a1395f29313caabce2422" plot: "Roger Willoughby is considered to be a leading expert on sports fishin…" genres: Array runtime: 120 SCORE: 1 _id: "573a1395f29313caabce2d63" plot: "The true story of the departure of the German occupiers from Paris in …" genres: Array runtime: 173 SCORE: 1 _id: "573a1395f29313caabce2db5" plot: "In this excoriating satire of the fashion industry, Polly Maggoo is a …" genres: Array runtime: 101 SCORE: 1 _id: "573a1395f29313caabce2ecc" plot: "A bitter aging couple with the help of alcohol, use a young couple to …" genres: Array runtime: 131
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
db.movies.aggregate([ { "$search": { "wildcard": { "path": "title", "query": "*\\?" } } }, { "$limit": 5 }, { "$project": { "_id": 0, "title": 1 } } ])
{ "title" : "Where Are My Children?" } { "title" : "Who Killed Cock Robin?" } { "title" : "What's Opera, Doc?" } { "title" : "Will Success Spoil Rock Hunter?" } { "title" : "Who Was That Lady?" }
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
In the :guilabel:`Aggregations` tab of the ``movies`` collection, configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click :guilabel:`Add Stage` to add additional stages. .. list-table:: :header-rows: 1 :widths: 25 75 * - Pipeline Stage - Query * - ``$search`` - .. code-block:: javascript { "wildcard": { "query": "*\\?", "path": "title" } } * - ``$limit`` - .. code-block:: javascript 5 * - ``$project`` - .. code-block:: javascript { "_id": 0, "title": 1, }
{ "title" : "Where Are My Children?" } { "title" : "Who Killed Cock Robin?" } { "title" : "What's Opera, Doc?" } { "title" : "Will Success Spoil Rock Hunter?" } { "title" : "Who Was That Lady?" }
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using MongoDB.Driver.Search; public class WildcardEscapeCharacter { 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.Wildcard(movie => movie.Title, "*\\?")) .Project<MovieDocument>(Builders<MovieDocument>.Projection .Include(movie => movie.Title) .Exclude(movie => movie.Id)) .Limit(5) .ToList(); // print results foreach (var movie in results) { Console.WriteLine(movie.ToJson()); } } } [ ]public class MovieDocument { [ ] public ObjectId Id { get; set; } public string Title { get; set; } }
{ "title" : "Where Are My Children?" } { "title" : "Who Killed Cock Robin?" } { "title" : "What's Opera, Doc?" } { "title" : "Will Success Spoil Rock Hunter?" } { "title" : "Who Was That Lady?" }
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { // connect to your Atlas cluster client, err := mongo.Connect(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{{"wildcard", bson.D{{"path", "title"}, {"query", "*\\?"}}}}}} limitStage := bson.D{{"$limit", 5}} 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) } }
[{title Where Are My Children?}] [{title Who Killed Cock Robin?}] [{title What's Opera, Doc?}] [{title Will Success Spoil Rock Hunter?}] [{title Who Was That Lady?}]
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
import static com.mongodb.client.model.Filters.eq; 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 WildcardEscapeCharacter { 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("query", "*\\?").append("path", "title"); // run pipeline and print results collection.aggregate(Arrays.asList( eq("$search", eq("wildcard", agg)), limit(5), project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson())); } } }
{"title": "Where Are My Children?"} {"title": "Who Killed Cock Robin?"} {"title": "What's Opera, Doc?"} {"title": "Will Success Spoil Rock Hunter?"} {"title": "Who Was That Lady?"}
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
import com.mongodb.client.model.Aggregates.limit import com.mongodb.client.model.Aggregates.project import com.mongodb.client.model.Filters.eq 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("query", "*\\?").append("path", "title") val resultsFlow = collection.aggregate<Document>( listOf( eq("\$search", eq("wildcard", agg)), limit(5), project(fields( excludeId(), include("title") )) ) ) resultsFlow.collect { println(it) } } mongoClient.close() }
Document{{title=Who Are You, Polly Magoo?}} Document{{title=Where Were You When the Lights Went Out?}} Document{{title=Why Does Herr R. Run Amok?}} Document{{title=What's Up, Doc?}} Document{{title=Who Is Killing the Great Chefs of Europe?}}
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
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: {wildcard: {query: "*\\?", path: "title"}}}, {$limit: 5}, {$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);
{ title: 'Where Are My Children?' } { title: 'Who Killed Cock Robin?' } { title: "What's Opera, Doc?" } { title: 'Will Success Spoil Rock Hunter?' } { title: 'Who Was That Lady?' }
Search Testerは返されるドキュメントのすべてのフィールドを表示しない可能性があります。クエリパスで指定したフィールドを含む、すべてのフィールドを表示するには、結果のドキュメントを展開します。
import pymongo # connect to your Atlas cluster client = pymongo.MongoClient('<connection-string>') # define pipeline pipeline = [ {"$search": {"wildcard": {"query": "*\\?", "path": "title"}}}, {"$limit": 5}, {"$project": {"_id": 0, "title": 1}}, ] # run pipeline result = client["sample_mflix"]["movies"].aggregate(pipeline) # print results for i in result: print(i)
{'title': 'Where Are My Children?'} {'title': 'Who Killed Cock Robin?'} {'title': "What's Opera, Doc?"} {'title': 'Will Success Spoil Rock Hunter?'} {'title': 'Who Was That Lady?'}
次のクエリでは、$searchMeta
ステージを使用して、title
フィールド内の任意の場所に summer
という語を含む映画を検索し、ジャンルごとにその条件に一致する映画の数を取得します。
db.movies.aggregate([ { "$searchMeta": { "facet": { "operator": { "wildcard": { "path": "title", "query": "*summer*" } }, "facets": { "genresFacet": { "type": "string", "path": "genres" } } } } } ])
[ { count: { lowerBound: Long('6') }, facet: { genresFacet: { buckets: [ { _id: 'Comedy', count: Long('5') }, { _id: 'Fantasy', count: Long('3') }, { _id: 'Romance', count: Long('3') }, { _id: 'Drama', count: Long('2') }, { _id: 'Horror', count: Long('1') }, { _id: 'Mystery', count: Long('1') } ] } } } ]