Docs Menu
Docs Home
/
MongoDB Atlas
/ /

Atlas Search에서 패싯을 사용하는 방법

이 페이지의 내용

  • 전제 조건
  • 패싯에 대한 Atlas 검색 인덱스 만들기
  • 컬렉션 검색
  • 학습 계속하기

이 튜토리얼에서는 sample_mflix.movies 컬렉션의 문자열, 날짜 및 숫자 필드에 패싯 정의를 사용하여 인덱스를 생성하는 방법을 설명합니다. 문자열 필드의 값과 날짜 및 숫자 필드의 범위를 기준으로 그룹화된 결과와 각 그룹의 개수를 얻기 위해 해당 필드에 대해 Atlas Search 쿼리를 실행하는 방법을 보여 줍니다. 다음 단계를 따르세요.

  1. sample_mflix.movies collection의 genres, releasedyear 필드에 패싯 정의가 있는 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 컬렉션의 genres, year, released 필드에 Atlas Search 인덱스를 생성합니다.

1
  1. 아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.

  2. 아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.

  3. 아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.

    클러스터 페이지가 표시됩니다.

2

사이드바, Data Explorer 또는 클러스터 세부 정보 페이지에서 Atlas Search 페이지로 이동할 수 있습니다.

  1. 사이드바에서 Services 제목 아래의 Atlas Search를 클릭합니다.

    참고

    클러스터가 없는 경우 Create cluster 을 클릭하여 클러스터를 생성하십시오. 자세히 알아보려면 클러스터 생성 을 참조하세요.

  2. Select data source 드롭다운에서 클러스터를 선택하고 Go to Atlas Search를 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. cluster의 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 정의는 필드 유형으로 정적으로 인덱싱하고 컬렉션 의 각 문서 에서 지원되는 유형의 다른 필드를 동적으로 인덱싱합니다.Visual Editor JSON Editor Atlas user 인터페이스에서 Atlas Search 또는 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 컬렉션에 대해 샘플 쿼리를 실행하여 genreyear 필드를 버킷으로 그룹화합니다. 성능을 최적화하려면:

  • facet 메타데이터만 필요한 경우 $searchMeta 단계를 사용합니다.

  • 쿼리 결과와 facet 메타데이터를 모두 조회하려면 $search 단계를 사용하세요.

1
  1. 아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.

  2. 아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.

  3. 아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.

    Clusters(클러스터) 페이지가 표시됩니다.

2

사이드바, Data Explorer 또는 클러스터 세부 정보 페이지에서 Atlas Search 페이지로 이동할 수 있습니다.

  1. 사이드바에서 Services 제목 아래의 Atlas Search를 클릭합니다.

    참고

    클러스터가 없는 경우 Create cluster 을 클릭하여 클러스터를 생성하십시오. 자세히 알아보려면 클러스터 생성 을 참조하세요.

  2. Select data source 드롭다운에서 클러스터를 선택하고 Go to Atlas Search를 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. cluster의 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일 근처에 개봉된 영화를 검색합니다. 약 3개월의 origin 로부터의 pivot 기간을 지정합니다. genres, year 필드에 대한 메타데이터를 요청합니다. 쿼리는 다음을 카운트합니다.

  • genres 문자열 배열 필드에 있는 각 장르의 영화 수입니다.

  • 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 기간 내의 영화를 찾는 근처를 검색합니다.

  • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

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를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.

2

Database 화면에서 sample_mflix 데이터베이스를 클릭한 다음 movies collection을 클릭합니다.

3

쿼리는 다음과 같은 searchMeta 연산자 절을 사용합니다.

  • 1921년 11월 11일부터 약 3개월 이내에 개봉한 영화를 검색하기 위해 origin 에서 pivot 기간 내의 영화를 찾는 근처를 검색합니다.

  • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.

  1. Aggregations 탭을 클릭합니다.

  2. Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    파이프라인 단계
    쿼리

    $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 기간 내의 영화를 찾는 근처를 검색합니다.

    • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    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 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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 절을 사용하여 collection을 쿼리합니다:

      • 1921년 11월 11일부터 약 3개월 이내에 개봉한 영화를 검색하기 위해 origin 에서 pivot 기간 내의 영화를 찾는 근처를 검색합니다.

      • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    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 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  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 절을 사용하여 collection을 쿼리합니다:

      • 1921년 11월 11일부터 약 3개월 이내에 개봉한 영화를 검색하기 위해 origin 에서 pivot 기간 내의 영화를 찾는 근처를 검색합니다.

      • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    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 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  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 기간 내의 영화를 찾는 근처를 검색합니다.

      • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

    • AggregateFlow 인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    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 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  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를 가져옵니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 searchMeta 절을 사용하여 collection을 쿼리합니다:

      • 1921년 11월 11일부터 약 3개월 이내에 개봉한 영화를 검색하기 위해 origin 에서 pivot 기간 내의 영화를 찾는 근처를 검색합니다.

      • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    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 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  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 모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여 pymongoAtlas에 연결하는 데 필요합니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음을 사용하여 컬렉션을 쿼리합니다.

      • 1921년 11월 11일부터 약 3개월 이내에 개봉한 영화를 검색하기 위해 origin 에서 pivot 기간 내의 영화를 찾는 근처를 검색합니다.

      • facetsgenres 문자열 배열 필드에서 각 장르별 영화 수와 1910년부터 1939년까지의 연도에 해당하는 영화 수를 요청함

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    이 쿼리는 $searchMeta 를 사용하거나 SEARCH_META 집계 변수를 사용하여 $search 를 사용하여 실행할 수 있습니다.

    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 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  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}
    ]
    }
    }
    }
    }

결과에는 두 가지 유형의 패싯 검색에 대한 메타데이터 결과가 표시됩니다. genresFacet 문서에는 각 장르의 영화 수가 표시되고 yearFacet 문서에는 경계 내에 있는 영화 수가 표시됩니다.

  • 1910, 1910이 하한값(포함)입니다.

  • 1920버킷에 대한 배타적 상한과 이 1910 1920 버킷에 대한 포괄적 하한입니다.

  • 1930버킷에 대한 배타적 상한과 이 1920 1930 버킷에 대한 포괄적 하한입니다.

코스동영상을 통해 Atlas Search의 패싯에 대해 자세히 알아볼 수 있습니다.

Atlas Search에서 패싯을 사용하는 방법에 대해 자세히 알아보려면 MongoDB University의 Intro To MongoDB 과정 9단원을 수강하세요. 1.5시간 분량인 이 단원에는 Atlas Search에 대한 개요와 Atlas Search 인덱스 만들기, 복합 연산자를 사용한 $search 쿼리 실행, facet을 사용한 결과 그룹화에 대한 강의가 포함되어 있습니다.

이 동영상을 따라 가며 쿼리에서 숫자 및 문자열 패싯 을 만들어 사용하여 결과를 그룹화하고 그룹 내 결과 수를 검색하는 방법을 알아보세요.

소요 시간: 11분

돌아가기

자동 완성 기능