Docs Menu
Docs Home
/
MongoDB Atlas
/ /

Atlas Searchでのファセットの使用方法

項目一覧

  • 前提条件
  • ファセットの Atlas Search インデックスの作成
  • コレクションを検索
  • 学び続ける

このチュートリアルでは、{3 stringsample_mflix.moviesコレクション内の 、日付、数値フィールドに ファセット定義 を使用してインデックスを作成する方法について説明します。string フィールドの値でグループ化され、日付フィールドと数値フィールドの範囲でグループ化された結果をこれらのフィールドに対して Atlas Search クエリを実行する方法を示します。これらの各グループのカウントを含む。 次の手順が必要です。

  1. sample_mflix.moviesコレクションのgenresreleasedyearフィールドにファセット定義を使用して Atlas Search インデックスを設定します。

  2. sample_mflix.moviesコレクションのreleasedフィールドに対して Atlas Search クエリを実行し、 genresフィールドの値でグループ化され、 yearフィールドの範囲でグループ化された結果を取得します。

Atlas Search インデックスを作成するには、プロジェクトに対するProject Data Access Admin以上のアクセス権が必要です。

これらのチュートリアルを完了するには、 Atlas Search チュートリアルページに記載されている前提条件に加えて、次のいずれかのバージョンを実行している Atlas クラスターが必要です。

  • MongoDB 5.0.4+

  • MongoDB 6.0+

  • MongoDB 7.0+

このセクションでは、 sample_mflix.moviesコレクションのgenresyear 、およびreleasedフィールドに Atlas Search インデックスを作成します。

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

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

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

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

2

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

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

    注意

    クラスターがない場合は、Create clusterをクリックしてクラスターを作成してください。詳細については、「 クラスターの作成 」を参照してください。

  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
4

ページで次の選択を行い、Next をクリックしてください。

Search Type

Atlas Search のインデックスタイプを選択します。

Index Name and Data Source

以下の情報を指定してください。

  • Index Name: facet-tutorial

  • Database and Collection:

    • sample_mflix database

    • movies コレクション

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.
5

動的マッピングまたは静的マッピングを使用する Atlas Search インデックスを作成できます。 動的マッピングと静的マッピングについて詳しくは、「静的マッピングと動的マッピング 」を参照してください。

次のインデックス定義では、genres フィールドをstringFacet タイプとして静的にインデックス化し、 moviesコレクション内の各ドキュメントでサポートされているタイプの他のフィールドを動的にインデックス化します。 Atlas SearchVisual Editor または Atlas SearchJSON Editor を使用して、Atlas ユーザー インターフェースで Atlas Search を使用して、インデックスを作成できます。

  1. [Next をクリックし、[Review Your Index] をクリックします。

  2. [Field Mappings] セクションの下の [Add Field Mapping] をクリックします。

  3. [Customzed COnfiguration をクリックし、ドロップダウンから以下を選択します。

    Field Name

    genres

    Data Type

    StringFacet

  4. [Add をクリックし、[Save Changes] をクリックします。

  1. [Next] をクリックします。

  2. インデックスの定義を確認します。

    インデックス定義は、次のようになります。

    {
    "mappings": {
    "dynamic": true,
    "fields": {
    "genres": {
    "type": "stringFacet"
    }
    }
    }
    }
  3. [Next] をクリックします。

6
7

インデックスが作成中であることを知らせるモーダル ウィンドウが表示されます。Close ボタンをクリックします。

8

インデックスの構築には約 1 分かかります。 作成している間、 Status列にはBuild in Progressと表示されます。 作成が完了すると、 Status列にはActiveと表示されます。


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


ファセットは、$searchおよび$searchMetaステージを使用するクエリで使用できます。このセクションでは、Atlas クラスターに接続し、$searchMeta または $search ステージを使用して sample_mflix.movies コレクションに対してサンプルクエリを実行し、genre フィールドと year フィールドをバケットにグループ化します。パフォーマンスを最適化するには、

  • facetメタデータのみが必要な場合は、$searchMeta ステージを使用してください。

  • クエリ結果とfacetメタデータの両方を検索する場合は、$searchステージを使用してください。

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

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

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

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

2

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

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

    注意

    クラスターがない場合は、Create clusterをクリックしてクラスターを作成してください。詳細については、「 クラスターの作成 」を参照してください。

  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

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

4

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

5

クエリを実行するには、次のクエリをコピーしてQuery Editorに貼り付け、[ Searchをクリックします。

次のクエリは、1921 年 11 月 11 日前後にリリースされた映画を検索します。 originから約 3 か月のpivotの距離を指定します。 genresyearフィールドと フィールドのメタデータをリクエストします。クエリは、次のカウントを要求します。

  • genres string 配列フィールド内の各ジャンルの映画の数

  • 1910 年から 1939 年までの映画の本数

[
{
"$searchMeta": {
"index": "facet-tutorial",
"facet": {
"operator": {
"near": {
"path": "released",
"origin": ISODate("1921-11-01T00:00:00.000+00:00"),
"pivot": 7776000000
}
},
"facets": {
"genresFacet": {
"type": "string",
"path": "genres"
},
"yearFacet" : {
"type" : "number",
"path" : "year",
"boundaries" : [1910,1920,1930,1940]
}
}
}
}
}
]
6

Search Testerでは、結果内のフィールドのすべての値が表示されない場合があります。 結果内のフィールドのすべての値を表示するには、フィールドを展開します。

Atlas Search によって、 ページに次の結果が表示されます。

count: Object
lowerBound: 20878
facet: Object
genresFacet: Object
buckets: Array (10)
0: Object
_id: "Drama"
count: 12149
1: Object
_id: "Comedy"
count: 6436
2: Object
_id: "Romance"
count: 3274
3: Object
_id: "Crime"
count: 2429
4: Object
_id: "Thriller"
count: 2400
5: Object
_id: "Action"
count: 2349
6: Object
_id: "Adventure"
count: 1876
7: Object
_id: "Documentary"
count: 1755
8: Object
_id: "Horror"
count: 1432
9: Object
_id: "Biography"
count: 1244
yearFacet: Object
buckets: Array (3)
0: Object
_id: 1910
count: 14
1: Object
_id: 1920
count: 47
2: Object
_id: 1930
count: 238
1

ターミナル ウィンドウでmongoshを開き、クラスターに接続します。 接続の詳細な手順については、「 mongosh経由での接続 」を参照してください。

2

mongoshプロンプトで次のコマンドを実行します。

use sample_mflix
3

サンプルクエリでは、次の要素を使用してコレクションをクエリします。

  • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

  • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

1db.movies.aggregate([
2 {
3 "$searchMeta": {
4 "index": "facet-tutorial",
5 "facet": {
6 "operator": {
7 "near": {
8 "path": "released",
9 "origin": ISODate("1921-11-01T00:00:00.000+00:00"),
10 "pivot": 7776000000
11 }
12 },
13 "facets": {
14 "genresFacet": {
15 "type": "string",
16 "path": "genres"
17 },
18 "yearFacet" : {
19 "type" : "number",
20 "path" : "year",
21 "boundaries" : [1910,1920,1930,1940]
22 }
23 }
24 }
25 }
26 }
27])
[
{
meta: {
count: { lowerBound: Long('20878') },
facet: {
genresFacet: {
buckets: [
{ _id: 'Drama', count: Long('12149') },
{ _id: 'Comedy', count: Long('6436') },
{ _id: 'Romance', count: Long('3274') },
{ _id: 'Crime', count: Long('2429') },
{ _id: 'Thriller', count: Long('2400') },
{ _id: 'Action', count: Long('2349') },
{ _id: 'Adventure', count: Long('1876') },
{ _id: 'Documentary', count: Long('1755') },
{ _id: 'Horror', count: Long('1432') },
{ _id: 'Biography', count: Long('1244') }
]
},
yearFacet: {
buckets: [
{ _id: 1910, count: Long('14') },
{ _id: 1920, count: Long('47') },
{ _id: 1930, count: Long('238') }
]
}
}
}
}
]
db.movies.aggregate([
{
"$search": {
"index": "facet-tutorial",
"facet": {
"operator": {
"near": {
"path": "released",
"origin": ISODate("1921-11-01T00:00:00.000+00:00"),
"pivot": 7776000000
}
},
"facets": {
"genresFacet": {
"type": "string",
"path": "genres"
},
"yearFacet": {
"type": "number",
"path": "year",
"boundaries" : [1910,1920,1930,1940]
}
}
}
}
},
{
"$facet": {
"meta": [
{"$replaceWith": "$$SEARCH_META"},
{"$limit": 1}
]
}
},
{
"$set": {
"meta": {
"$arrayElemAt": ["$meta", 0]
}
}
}
])
[
{
meta: {
count: { lowerBound: Long('20878') },
facet: {
genresFacet: {
buckets: [
{ _id: 'Drama', count: Long('12149') },
{ _id: 'Comedy', count: Long('6436') },
{ _id: 'Romance', count: Long('3274') },
{ _id: 'Crime', count: Long('2429') },
{ _id: 'Thriller', count: Long('2400') },
{ _id: 'Action', count: Long('2349') },
{ _id: 'Adventure', count: Long('1876') },
{ _id: 'Documentary', count: Long('1755') },
{ _id: 'Horror', count: Long('1432') },
{ _id: 'Biography', count: Long('1244') }
]
},
yearFacet: {
buckets: [
{ _id: 1910, count: Long('14') },
{ _id: 1920, count: Long('47') },
{ _id: 1930, count: Long('238') }
]
}
}
}
}
]
1

MongoDB Compass を開き、クラスターに接続します。 接続の詳細な手順については、「 Compass 経由での接続 」を参照してください。

2

Database画面で、 sample_mflixデータベースをクリックし、 moviesコレクションをクリックします。

3

クエリでは、次のsearchMeta演算子句を使用します。

  • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

  • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

MongoDB Compass でこのクエリを実行するには:

  1. [Aggregations] タブをクリックします。

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

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

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

    $searchMeta

    {
    index: 'facet-tutorial',
    facet: {
    operator: {
    near: {
    path: 'released',
    origin: ISODate("1921-11-01T00:00:00.000+00:00"),
    pivot: 7776000000
    }
    },
    facets: {
    genresFacet: {
    type: 'string',
    path: 'genres'
    },
    yearFacet: {
    type: 'number',
    path: 'year',
    boundaries: [1910,1920,1930,1940]
    }
    }
    }
    }
    パイプラインステージ
    クエリ

    $search

    {
    "index": "facet-tutorial",
    "facet": {
    "operator": {
    "near": {
    "path": "released",
    "origin": ISODate("1921-11-01T00:00:00.000+00:00"),
    "pivot": 7776000000
    }
    },
    "facets": {
    "genresFacet": {
    "type": "string",
    "path": "genres"
    },
    "yearFacet": {
    "type": "number",
    "path": "year",
    "boundaries" : [1910,1920,1930,1940]
    }
    }
    }
    }

    $facet

    {
    meta: [
    {
    $replaceWith: "$$SEARCH_META"
    },
    {
    $limit: 1
    }
    ]
    }

    $set

    {
    meta: {
    $arrayElemAt: ["$meta", 0]
    }
    }

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

count: Object
lowerBound: 20878
facet: Object
genresFacet: Object
buckets: Array (10)
0: Object
_id: "Drama"
count: 12149
1: Object
_id: "Comedy"
count: 6436
2: Object
_id: "Romance"
count: 3274
3: Object
_id: "Crime"
count: 2429
4: Object
_id: "Thriller"
count: 2400
5: Object
_id: "Action"
count: 2349
6: Object
_id: "Adventure"
count: 1876
7: Object
_id: "Documentary"
count: 1755
8: Object
_id: "Horror"
count: 1432
9: Object
_id: "Biography"
count: 1244
yearFacet: Object
buckets: Array (3)
0: Object
_id: 1910
count: 14
1: Object
_id: 1920
count: 47
2: Object
_id: 1930
count: 238
1
  1. facet-query-example という新しいディレクトリを作成し、dotnet new コマンドでプロジェクトを初期化します。

    mkdir facet-query-example
    cd facet-query-example
    dotnet new console
  2. .NET/C# ドライバーを依存関係としてプロジェクトに追加します。

    dotnet add package MongoDB.Driver
2
  1. Program.cs ファイルの内容を、次のコードで置き換えます。

    サンプルクエリでは、次の要素を使用してコレクションをクエリします。

    • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

    • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class FacetExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // declare data for date and number fields
    23 var originDate = new DateTime(1921, 11, 01, 0, 0, 0, DateTimeKind.Utc);
    24
    25 // define and run pipeline
    26 var results = moviesCollection.Aggregate()
    27 .SearchMeta(Builders<MovieDocument>.Search.Facet(
    28 Builders<MovieDocument>.Search.Near(movie => movie.Released, originDate, 7776000000),
    29 Builders<MovieDocument>.SearchFacet.String("genresFacet", movie => movie.Genres, 10),
    30 Builders<MovieDocument>.SearchFacet.Number("yearFacet", movie => movie.Year, 1910, 1920, 1930, 1940)),
    31 indexName: "facet-tutorial")
    32 .Single();
    33
    34 // print results
    35 Console.WriteLine(results.ToJson());
    36 }
    37}
    38
    39[BsonIgnoreExtraElements]
    40public class MovieDocument
    41{
    42 [BsonIgnoreIfDefault]
    43 public ObjectId Id { get; set; }
    44 public string [] Genres { get; set; }
    45 public DateTime Released { get; set; }
    46 public int Year { get; set; }
    47}
    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6using System;
    7
    8public class FacetExample
    9{
    10 private const string MongoConnectionString = "<your-connection-string>";
    11
    12 public static void Main(string[] args)
    13 {
    14 // Register camelCase conventions for document mapping
    15 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    16 ConventionRegistry.Register("CamelCase", camelCaseConvention, t => true);
    17
    18 // Connect to your MongoDB Atlas cluster
    19 var mongoClient = new MongoClient(MongoConnectionString);
    20 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    21 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    22
    23 // Define the origin date for the `near` operator
    24 var originDate = new DateTime(1921, 11, 01, 0, 0, 0, DateTimeKind.Utc);
    25
    26 // Create an array of BsonValues for the number boundaries
    27 var yearBoundaries = new BsonArray { 1910, 1920, 1930, 1940 };
    28
    29 // Define the $search stage
    30 var searchStage = Builders<MovieDocument>.Search.Facet(
    31 Builders<MovieDocument>.Search.Near(
    32 "released", // The field to search
    33 origin: originDate, // Starting date
    34 pivot: 7776000000 // Pivot (milliseconds)
    35 ),
    36 Builders<MovieDocument>.SearchFacet.String(
    37 "genresFacet", // Name of the string facet
    38 "genres" // The field to facet on
    39 ),
    40 Builders<MovieDocument>.SearchFacet.Number(
    41 "yearFacet", // Name of the number facet
    42 "year", // The field to facet on
    43 yearBoundaries
    44 )
    45 );
    46
    47 // Step 2: Aggregate pipeline implementationdd
    48 var pipeline = moviesCollection.Aggregate()
    49 .Search(searchStage, indexName: "facet-tutorial")
    50 .AppendStage<BsonDocument>(new BsonDocument
    51 {
    52 { "$facet", new BsonDocument
    53 {
    54 { "meta", new BsonArray
    55 {
    56 new BsonDocument { { "$replaceWith", "$$SEARCH_META" } },
    57 new BsonDocument { { "$limit", 1 } }
    58 }
    59 }
    60 }
    61 }
    62 })
    63 .AppendStage<BsonDocument>(new BsonDocument
    64 {
    65 { "$set", new BsonDocument
    66 {
    67 { "meta", new BsonDocument
    68 {
    69 { "$arrayElemAt", new BsonArray { "$meta", 0 } }
    70 }
    71 }
    72 }
    73 }
    74 })
    75 .ToList();
    76
    77 // Step 3: Output results
    78 foreach (var result in pipeline)
    79 {
    80 Console.WriteLine(result.ToJson());
    81 }
    82 }
    83}
    84
    85[BsonIgnoreExtraElements]
    86public class MovieDocument
    87{
    88 [BsonIgnoreIfDefault]
    89 public ObjectId Id { get; set; }
    90 public string[] Genres { get; set; }
    91 public DateTime Released { get; set; }
    92 public int Year { get; set; }
    93}
  2. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

3
dotnet run facet-query-example.csproj
{
"meta" : {
"count" : { "lowerBound" : 20878 },
"facet" : {
"genresFacet" : {
"buckets" : [
{ "_id" : "Drama", "count" : 12149 },
{ "_id" : "Comedy", "count" : 6436 },
{ "_id" : "Romance", "count" : 3274 },
{ "_id" : "Crime", "count" : 2429 },
{ "_id" : "Thriller", "count" : 2400 },
{ "_id" : "Action", "count" : 2349 },
{ "_id" : "Adventure", "count" : 1876 },
{ "_id" : "Documentary", "count" : 1755 },
{ "_id" : "Horror", "count" : 1432 },
{ "_id" : "Biography", "count" : 1244 }
]
},
"yearFacet" : {
"buckets" : [
{ "_id" : 1910, "count" : 14 },
{ "_id" : 1920, "count" : 47 },
{ "_id" : 1930, "count" : 238 }
]
}
}
}
}
1
  1. facet-query.goという名前のファイルを作成します。

  2. 次のコードをコピーして、 facet-query.goファイルに貼り付けます。

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

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

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

    • 次の searchMeta 句を使用して、 コレクションをクエリします。

      • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

      • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

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

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{"$searchMeta", bson.M{
    26 "index": "facet-tutorial",
    27 "facet": bson.M{
    28 "operator": bson.M{
    29 "near": bson.M{
    30 "path": "released",
    31 "origin": time.Date(1921, time.November, 1, 0, 0, 0, 0, time.UTC),
    32 "pivot": 7776000000},
    33 },
    34 "facets": bson.M{
    35 "genresFacet": bson.M{
    36 "path": "genres",
    37 "type": "string"},
    38 "yearFacet": bson.M{
    39 "path": "year",
    40 "type": "number",
    41 "boundaries": bson.A{1910, 1920, 1930, 1940}},
    42 }}}}}
    43 // run pipeline
    44 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage})
    45 if err != nil {
    46 panic(err)
    47 }
    48
    49 // print results
    50 var results []bson.D
    51 if err = cursor.All(context.TODO(), &results); err != nil {
    52 panic(err)
    53 }
    54 for _, result := range results {
    55 fmt.Println(result)
    56 }
    57}
    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{"$search", bson.M{
    26 "index": "facet-tutorial",
    27 "facet": bson.M{
    28 "operator": bson.M{
    29 "near": bson.M{
    30 "path": "released",
    31 "origin": time.Date(1921, time.November, 1, 0, 0, 0, 0, time.UTC),
    32 "pivot": 7776000000},
    33 },
    34 "facets": bson.M{
    35 "genresFacet": bson.M{
    36 "path": "genres",
    37 "type": "string"},
    38 "yearFacet": bson.M{
    39 "path": "year",
    40 "type": "number",
    41 "boundaries": bson.A{1910, 1920, 1930, 1940}},
    42 },
    43 },
    44 }}}
    45
    46 facetStage:= bson.D{{"$facet", bson.D{
    47 {"meta", bson.A{
    48 bson.D{{"$replaceWith", "$$SEARCH_META"}},
    49 bson.D{{"$limit", 1}},
    50 }},
    51 }}}
    52 setStage:= bson.D{{"$set", bson.D{
    53 {"meta", bson.D{
    54 {"$arrayElemAt", bson.A{"$meta", 0}},
    55 }},
    56 }}}
    57
    58 // run pipeline
    59 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, facetStage, setStage})
    60 if err != nil {
    61 panic(err)
    62 }
    63
    64 // print results
    65 var results []bson.D
    66 if err = cursor.All(context.TODO(), &results); err != nil {
    67 panic(err)
    68 }
    69 for _, result := range results {
    70 fmt.Println(result)
    71 }
    72}
  3. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  4. 次のコマンドを実行して、コレクションをクエリします。

    go run facet-query.go
    [
    {count [
    {lowerBound 20878}
    ]}
    {facet [
    {genresFacet [
    {buckets [
    [{_id Drama} {count 12149}]
    [{_id Comedy} {count 6436}]
    [{_id Romance} {count 3274}]
    [{_id Crime} {count 2429}]
    [{_id Thriller} {count 2400}]
    [{_id Action} {count 2349}]
    [{_id Adventure} {count 1876}]
    [{_id Documentary} {count 1755}]
    [{_id Horror} {count 1432}]
    [{_id Biography} {count 1244}]
    ]}
    ]}
    {yearFacet [
    {buckets [
    [{_id 1910} {count 14}]
    [{_id 1920} {count 47}]
    [{_id 1930} {count 238}]
    ]}
    ]}
    ]}
    ]
1

junit

4.11以降のバージョン

mongodb-driver-sync

4.3.0以降のバージョン

slf4j-log4j12

1.7.30以降のバージョン

2
  1. FacetQuery.javaという名前のファイルを作成します。

  2. 次のコードをコピーして、 FacetQuery.javaファイルに貼り付けます。

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

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

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

    • 次の searchMeta 句を使用して、 コレクションをクエリします。

      • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

      • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

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

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

    1import com.mongodb.client.MongoClient;
    2import com.mongodb.client.MongoClients;
    3import com.mongodb.client.MongoCollection;
    4import com.mongodb.client.MongoDatabase;
    5import org.bson.Document;
    6
    7import java.time.Instant;
    8import java.util.Arrays;
    9import java.util.Date;
    10
    11public class FacetQuery {
    12 public static void main(String[] args) {
    13 // connect to your Atlas cluster
    14 String uri = "<connection-string>";
    15
    16 try (MongoClient mongoClient = MongoClients.create(uri)) {
    17 // set namespace
    18 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    19 MongoCollection<Document> collection = database.getCollection("movies");
    20
    21 // define pipeline
    22 Document agg = new Document("$searchMeta",
    23 new Document( "index", "facet-tutorial")
    24 .append("facet",
    25 new Document("operator",
    26 new Document("near",
    27 new Document("path", "released")
    28 .append("origin", Date.from(Instant.parse("1921-11-01T00:00:00.000+00:00")))
    29 .append("pivot", 7776000000L)))
    30 .append("facets",
    31 new Document("genresFacet",
    32 new Document("type", "string").append("path", "genres"))
    33 .append("yearFacet",
    34 new Document("type", "number").append("path", "year")
    35 .append("boundaries", Arrays.asList(1910, 1920, 1930, 1940))
    36 ))));
    37 // run pipeline and print results
    38 collection.aggregate(Arrays.asList(agg))
    39 .forEach(doc -> System.out.println(doc.toJson()));
    40
    41 }
    42 }
    43}
    1import com.mongodb.client.MongoClient;
    2import com.mongodb.client.MongoClients;
    3import com.mongodb.client.MongoCollection;
    4import com.mongodb.client.MongoDatabase;
    5import org.bson.Document;
    6
    7import java.util.Arrays;
    8import java.util.List;
    9
    10public class FacetQuery {
    11 public static void main(String[] args) {
    12 // connect to your Atlas cluster
    13 String uri = "<CONNECTION-STRING>";
    14
    15 try (MongoClient mongoClient = MongoClients.create(uri)) {
    16 // set namespace
    17 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    18 MongoCollection<Document> collection = database.getCollection("movies");
    19
    20 // define pipeline
    21 List<Document> agg = Arrays.asList(new Document("$search",
    22 new Document("index", "facet-tutorial")
    23 .append("facet", new Document("operator", new Document("near", new Document("path", "released")
    24 .append("origin", new java.util.Date(-1520035200000L))
    25 .append("pivot", 7776000000L)))
    26 .append("facets", new Document("genresFacet", new Document("type", "string")
    27 .append("path", "genres"))
    28 .append("yearFacet", new Document("type", "number")
    29 .append("path", "year")
    30 .append("boundaries", Arrays.asList(1910L, 1920L, 1930L, 1940L)))))),
    31 new Document("$facet", new Document("meta", Arrays.asList(new Document("$replaceWith", "$$SEARCH_META"),
    32 new Document("$limit", 1L)))),
    33 new Document("$set", new Document("meta", new Document("$arrayElemAt", Arrays.asList("$meta", 0L)))));
    34 // run pipeline and print results
    35 collection.aggregate(agg)
    36 .forEach(doc -> System.out.println(doc.toJson()));
    37
    38 }
    39 }
    40}

    注意

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

    package com.mongodb.drivers;
  3. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  4. FacetQuery.javaファイルをコンパイルして実行します。

    javac FacetQuery.java
    java FacetQuery
    {meta: {
    count: { lowerBound: Long('20878') },
    facet: {
    genresFacet: {
    buckets: [
    { _id: 'Drama', count: Long('12149') },
    { _id: 'Comedy', count: Long('6436') },
    { _id: 'Romance', count: Long('3274') },
    { _id: 'Crime', count: Long('2429') },
    { _id: 'Thriller', count: Long('2400') },
    { _id: 'Action', count: Long('2349') },
    { _id: 'Adventure', count: Long('1876') },
    { _id: 'Documentary', count: Long('1755') },
    { _id: 'Horror', count: Long('1432') },
    { _id: 'Biography', count: Long('1244') }
    ]
    },
    yearFacet: {
    buckets: [
    { _id: 1910, count: Long('14') },
    { _id: 1920, count: Long('47') },
    { _id: 1930, count: Long('238') }
    ]
    }
    }
    }}
1

mongodb-driver-kotlin-coroutine

4.10.0以降のバージョン

2
  1. FacetQuery.ktという名前のファイルを作成します。

  2. 次のコードをコピーして、 FacetQuery.ktファイルに貼り付けます。

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

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

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

    • 次の項目を使用して、コレクションをクエリします。

      • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

      • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

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

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

    1import com.mongodb.kotlin.client.coroutine.MongoClient
    2import kotlinx.coroutines.runBlocking
    3import org.bson.Document
    4import java.time.Instant
    5import java.util.*
    6
    7fun main() {
    8 // connect to your Atlas cluster
    9 val uri = "<connection-string>"
    10 val mongoClient = MongoClient.create(uri)
    11
    12 // set namespace
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define pipeline
    18 val agg = Document(
    19 "\$searchMeta",
    20 Document("index", "facet-tutorial")
    21 .append(
    22 "facet",
    23 Document(
    24 "operator",
    25 Document(
    26 "near",
    27 Document("path", "released")
    28 .append("origin", Date.from(Instant.parse("1921-11-01T00:00:00.000+00:00")))
    29 .append("pivot", 7776000000L)
    30 )
    31 )
    32 .append(
    33 "facets",
    34 Document(
    35 "genresFacet",
    36 Document("type", "string").append("path", "genres")
    37 )
    38 .append(
    39 "yearFacet",
    40 Document("type", "number").append("path", "year")
    41 .append("boundaries", listOf(1910, 1920, 1930, 1940))
    42 )
    43 )
    44 )
    45 )
    46
    47 // run pipeline and print results
    48 val resultsFlow = collection.aggregate<Document>(
    49 listOf(agg)
    50 )
    51 resultsFlow.collect { println(it) }
    52 }
    53 mongoClient.close()
    54}
    1import com.mongodb.kotlin.client.coroutine.MongoClient
    2import kotlinx.coroutines.flow.collect
    3import kotlinx.coroutines.runBlocking
    4import org.bson.Document
    5import java.time.Instant
    6import java.util.Date
    7
    8fun main() {
    9 // Connection URI for your MongoDB Atlas cluster
    10 val uri = "<connection-string>"
    11 val mongoClient = MongoClient.create(uri)
    12
    13 // Set namespace (database and collection)
    14 val database = mongoClient.getDatabase("sample_mflix")
    15 val collection = database.getCollection<Document>("movies")
    16
    17 runBlocking {
    18 // Define the aggregation pipeline
    19 val searchStage = Document("\$search", Document("index", "facet-tutorial")
    20 .append("facet", Document("operator", Document("near", Document("path", "released")
    21 // Replace +00:00 with Z
    22 .append("origin", Date.from(Instant.parse("1921-11-01T00:00:00.000Z")))
    23 .append("pivot", 7776000000L)))
    24 .append("facets", Document("genresFacet", Document("type", "string")
    25 .append("path", "genres"))
    26 .append("yearFacet", Document("type", "number").append("path", "year")
    27 .append("boundaries", listOf(1910, 1920, 1930, 1940))))))
    28
    29 val facetStage = Document("\$facet", Document("meta", listOf(
    30 Document("\$replaceWith", "\$\$SEARCH_META"),
    31 Document("\$limit", 1)
    32 )))
    33
    34 val setStage = Document("\$set", Document("meta", Document("\$arrayElemAt", listOf("\$meta", 0))))
    35
    36 // Run the aggregation pipeline and print results
    37 val resultsFlow = collection.aggregate<Document>(
    38 listOf(searchStage, facetStage, setStage)
    39 )
    40
    41 resultsFlow.collect { println(it.toJson()) } // Convert each result to JSON and print
    42 }
    43
    44 // Close the MongoDB client
    45 mongoClient.close()
    46}
  3. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  4. FacetQuery.ktファイルを実行します。

    IDE でFacetQuery.ktプログラムを実行すると、次の結果が出力されます。

    Document{{
    count=Document{{lowerBound=20878}},
    facet=Document{{
    genresFacet=Document{{
    buckets=[
    Document{{_id=Drama, count=12149}},
    Document{{_id=Comedy, count=6436}},
    Document{{_id=Romance, count=3274}},
    Document{{_id=Crime, count=2429}},
    Document{{_id=Thriller, count=2400}},
    Document{{_id=Action, count=2349}},
    Document{{_id=Adventure, count=1876}},
    Document{{_id=Documentary, count=1755}},
    Document{{_id=Horror, count=1432}},
    Document{{_id=Biography, count=1244}}
    ]
    }},
    yearFacet=Document{{
    buckets=[
    Document{{_id=1910, count=14}},
    Document{{_id=1920, count=47}},
    Document{{_id=1930, count=238}}
    ]
    }}
    }}
    }}
1
  1. facet-query.jsという名前のファイルを作成します。

  2. 次のコードをコピーして、 facet-query.jsファイルに貼り付けます。

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

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

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

    • 次の searchMeta 句を使用して、 コレクションをクエリします。

      • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

      • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

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

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11 await client.connect();
    12
    13 // set namespace
    14 const database = client.db("sample_mflix");
    15 const coll = database.collection("movies");
    16
    17 // define pipeline
    18 const agg = [{$searchMeta: {
    19 index: "facet-tutorial",
    20 facet: {
    21 operator: {
    22 near: {path: "released", origin: new Date("1921-11-01T00:00:00.000Z"), pivot: 7776000000}
    23 },
    24 facets: {
    25 genresFacet: {type: "string", path: "genres"},
    26 yearFacet: {type: "number", path: "year",boundaries: [1910,1920,1930,1940]}
    27 }}}}];
    28 // run pipeline
    29 const result = coll.aggregate(agg);
    30
    31 // print results
    32 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
    33 } finally {
    34 await client.close();
    35 }
    36}
    37run().catch(console.dir);
    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri = "<connection-string>";
    5
    6const client = new MongoClient(uri);
    7
    8async function run() {
    9 try {
    10 await client.connect();
    11
    12 // set namespace
    13 const database = client.db("sample_mflix");
    14 const coll = database.collection("movies");
    15
    16 // define pipeline
    17 const agg = [
    18 {
    19 '$search': {
    20 'index': "facet-tutorial",
    21 'facet': {
    22 'operator': {
    23 'near': {
    24 'path': 'released',
    25 'origin': new Date('Tue, 01 Nov 1921 00:00:00 GMT'),
    26 'pivot': 7776000000
    27 }
    28 },
    29 'facets': {
    30 'genresFacet': {
    31 'type': 'string',
    32 'path': 'genres'
    33 },
    34 'yearFacet': {
    35 'type': 'number',
    36 'path': 'year',
    37 'boundaries': [1910, 1920, 1930, 1940]
    38 }
    39 }
    40 }
    41 }
    42 }, {
    43 '$facet': {
    44 'meta': [
    45 {
    46 '$replaceWith': '$$SEARCH_META'
    47 }, {
    48 '$limit': 1
    49 }
    50 ]
    51 }
    52 }, {
    53 '$set': {
    54 'meta': {
    55 '$arrayElemAt': ['$meta', 0]
    56 }
    57 }
    58 }
    59 ];
    60 // run pipeline
    61 const result = coll.aggregate(agg);
    62
    63 // print results
    64 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
    65 } finally {
    66 await client.close();
    67 }
    68}
    69run().catch(console.dir);
  3. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  4. 次のコマンドを実行して、コレクションをクエリします。

    node facet-query.js
    '{
    "meta":{
    "count":{"lowerBound":20878},
    "facet":{
    "genresFacet":{
    "buckets":[
    {"_id":"Drama","count":12149},
    {"_id":"Comedy","count":6436},
    {"_id":"Romance","count":3274},
    {"_id":"Crime","count":2429},
    {"_id":"Thriller","count":2400},
    {"_id":"Action","count":2349},
    {"_id":"Adventure","count":1876},
    {"_id":"Documentary","count":1755},
    {"_id":"Horror","count":1432},
    {"_id":"Biography","count":1244}
    ]
    },
    "yearFacet":{
    "buckets":[
    {"_id":1910,"count":14},
    {"_id":1920,"count":47},
    {"_id":1930,"count":238}
    ]
    }
    }
    }
    }'
1
  1. facet-query.pyという名前のファイルを作成します。

    touch facet-query.py
  2. 次のコードをコピーして、 facet-query.pyファイルに貼り付けます。

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

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

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

    • 次の項目を使用して、コレクションをクエリします。

      • に近いでは、1921 年 11 月 11 日から約 3 か月間にoriginからのpivotの距離でリリースされた映画を検索します

      • facets genres string 配列フィールドの各ジャンルの映画の数と、 1910から1939までの 年間の映画の数をリクエストします

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

    このクエリは、$searchMeta または $search を使用して、SEARCH_META 集計変数を用いて実行できます。

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient('<connection-string>')
    6
    7# define pipeline
    8pipeline = [{"$searchMeta": {
    9 "index": "facet-tutorial",
    10 "facet": {
    11 "operator": {
    12 "near": {"path": "released", "origin": datetime.datetime(1921, 11, 1, 0, 0, 0, 0), "pivot": 7776000000}
    13 },
    14 "facets": {
    15 "genresFacet": {"type": "string", "path": "genres"},
    16 "yearFacet" : {"type" : "number", "path" : "year", "boundaries" : [1910,1920,1930,1940]}
    17 }}}}]
    18# run pipeline
    19result = client["sample_mflix"]["movies"].aggregate(pipeline)
    20
    21# print results
    22for i in result:
    23 print(i)
    1import pymongo
    2from datetime import datetime, timezone # Import timezone for tzinfo=timezone.utc
    3
    4# Connect to your Atlas cluster
    5client = pymongo.MongoClient("<connection-string>")
    6
    7# Define pipeline
    8pipeline = [{
    9 '$search': {
    10 'index': 'facet-tutorial',
    11 'facet': {
    12 'operator': {
    13 'near': {
    14 'path': 'released',
    15 'origin': datetime(1921, 11, 1, 0, 0, 0, tzinfo=timezone.utc), # Corrected timezone
    16 'pivot': 7776000000
    17 }
    18 },
    19 'facets': {
    20 'genresFacet': {
    21 'type': 'string', 'path': 'genres'
    22 },
    23 'yearFacet': {
    24 'type': 'number', 'path': 'year', 'boundaries': [1910, 1920, 1930, 1940]
    25 }
    26 }
    27 }
    28 }
    29}, {
    30 '$facet': {
    31 'meta': [
    32 {'$replaceWith': '$$SEARCH_META'},
    33 {'$limit': 1}
    34 ]
    35 }
    36}, {
    37 '$set': {
    38 'meta': {'$arrayElemAt': ['$meta', 0]}
    39 }
    40}]
    41# Run pipeline
    42result = client["sample_mflix"]["movies"].aggregate(pipeline)
    43
    44# Print results
    45for doc in result:
    46 print(doc)
  3. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  4. 次のコマンドを実行して、コレクションをクエリします。

    python facet-query.py
    {
    'meta': {
    'count': {'lowerBound': 20878},
    'facet': {
    'genresFacet': {
    'buckets': [
    {'_id': 'Drama', 'count': 12149},
    {'_id': 'Comedy', 'count': 6436},
    {'_id': 'Romance', 'count': 3274},
    {'_id': 'Crime', 'count': 2429},
    {'_id': 'Thriller', 'count': 2400},
    {'_id': 'Action', 'count': 2349},
    {'_id': 'Adventure', 'count': 1876},
    {'_id': 'Documentary', 'count': 1755},
    {'_id': 'Horror', 'count': 1432},
    {'_id': 'Biography', 'count': 1244}
    ]
    },
    'yearFacet': {
    'buckets': [
    {'_id': 1910, 'count': 14},
    {'_id': 1920, 'count': 47},
    {'_id': 1930, 'count': 238}
    ]
    }
    }
    }
    }

結果には、2 種類のファセット検索のメタデータ結果が表示されます。 genresFacetドキュメントには各ジャンルの映画の数が表示され、 yearFacetドキュメントにはその境界内の映画の数が表示されます。

  • 1910: 1910バケットの下限値を含む

  • 1920: 1910バケットの 排他的上限であり、 1920バケットの下限

  • 1930: 1920バケットの 排他的上限であり、 1930バケットの下限

Atlas Search のファセットについての詳細は、コースまたはビデオでご覧ください。

Atlas Search でファセットの使用の詳細については、 MongoDB University の Intro MongoDB コースユニット9を受講してください。 1.5時間のユニットには、Atlas Search の概要、Atlas Search インデックスの作成、複合演算子を使用した$searchクエリの実行、 facetを使用した結果のグループ化に関するレッスンが含まれています。

このビデオでは、クエリ内で数値ファセットと stringファセットを作成して使用し、結果をグループ化し、グループ内の結果の数を取得する方法について説明します。

所要時間: 11 分

戻る

オートコンプリート