Atlas Search 결과 정렬 방법
이 튜토리얼에서는 sample_mflix.movies
컬렉션의 숫자, 날짜 및 문자열 필드를 기준으로 오름차순 또는 내림차순으로 Atlas Search 결과를 정렬하는 방법을 설명합니다. 또한 대소문자를 구분하지 않고 Atlas Search 결과를 정렬하는 방법도 설명합니다. 컬렉션에 Atlas Search 인덱스를 생성할 때 문자열 필드의 값을 소문자로 정규화하도록 인덱스를 구성할 수 있습니다. 이를 통해 정렬된 필드의 대소문자에 관계없이 쿼리 결과를 정렬할 수 있습니다.
Atlas Search sort
옵션의 기본 동작을 사용하여 숫자, 날짜, 문자열 필드를 기준으로 Atlas Search 결과를 정렬하는 방법을 보여주기 위해 튜토리얼에서 다음 단계를 안내합니다.
sample_mflix.movies
collection의 문자열 필드(title
), 날짜 필드(released
), 숫자 필드(awards.wins
)에 대한 Atlas Search 인덱스를 생성하여 이러한 필드에 대해 쿼리를 실행하고 이러한 필드를 기준으로 결과를 정렬합니다.sample_mflix.movies
collection 의title
,released
및awards.wins
필드에 대해 Atlas Search 쿼리를 실행하고 이러한 필드를 기준으로 결과를 오름차순 및 내림차순으로 정렬합니다.
Atlas Search sort
옵션을 사용하여 문자열 필드의 값을 소문자로 정규화하여 Atlas Search 결과를 정렬하는 방법을 설명하기 위해 해당 튜토리얼은 다음 단계를 보여줍니다.
샘플 문서를 Atlas 클러스터의
sample_mflix.movies
컬렉션에 로드합니다.쿼리를 실행하고 이 필드를 기준으로 결과를 정렬할 때 모두
title
이라는 문자열 필드에 Atlas Search 인덱스를 생성합니다.컬렉션의
title
필드에 대해 Atlas Search 쿼리를 실행하고 인덱싱된 필드를 기준으로 결과를 정렬합니다.
시작하기 전에 Atlas 클러스터가 필수구성 요소에 설명된 요건을 충족하는지 확인하십시오.
Atlas Search 인덱스를 생성하려면 프로젝트에 대한 Project Data Access Admin
이상의 액세스 권한이 있어야 합니다.
샘플 데이터 로드
기본 sort
동작을 사용하여 sample_mflix.movies
컬렉션의 문서를 번호, 날짜 및 문자열 필드별로 정렬하려면 이 섹션을 건너뛰고 컬렉션에 대한 인덱스 생성을 계속 진행하면 됩니다.
개요
대소문자에 관계없이 문서를 정렬하는 Atlas Search의 방법을 보여드리기 위해 샘플 문서를 제공합니다. 각 샘플 문서는 영화를 나타내며 영화 제목(소문자), 장르, 수상 횟수를 지정하는 세 개의 필드를 포함합니다. 이 섹션에서는 샘플 문서를 Atlas 클러스터의 sample_mflix.movies
컬렉션에 로드합니다. Atlas UI나 mongosh
를 사용하여 샘플 컬렉션을 로드할 수 있습니다.
절차
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
Collections 페이지로 이동합니다.
cluster의 Browse Collections 버튼을 클릭합니다.
데이터 탐색기 가 표시됩니다.
컬렉션을 Atlas 클러스터의 데이터베이스에 로드합니다.
Atlas UI 또는 mongosh
에서 컬렉션을 로드할 수 있습니다.
sample_mflix
데이터베이스를 확장하고movies
컬렉션을 선택합니다.컬렉션에 추가할 각 샘플 문서에 대해 다음을 수행합니다.
Insert Document을 클릭하고 기본 문서를 대체하기 위해 JSON 보기({})를 선택하세요.
다음 샘플 문서를 한 번에 하나씩 복사하여 붙여넣고 Insert 를 클릭하여 각 문서를 컬렉션에 추가합니다.
1 { 2 "genres": [ "Action", "Drama", "Thriller" ], 3 "title": "atomic train", 4 "awards": { "wins": 1, "nominations": 1 } 5 } 1 { 2 "genres": [ "Animation", "Adventure", "Family" ], 3 "title": "how to train your dragon", 4 "awards": { "wins": 32, "nominations": 51 } 5 }
연결하려는 클러스터에 대해 Connect를 클릭합니다.
Shell을 선택하고
mongosh
를 통해 클러스터에 연결하기 위한 단계를 완료하세요.자세한 내용은
mongosh
를 통한 연결을 참조하세요.mongosh
의sample_mflix
데이터베이스로 전환합니다.use sample_mflix switched to db sample_mflix mongosh
에서 다음 명령을 실행하여 선택한 데이터베이스에 컬렉션을 로드합니다.1 db.movies.insertMany([ 2 { 3 "_id": 1, 4 "genres": [ "Action", "Drama", "Thriller" ], 5 "title": "atomic train", 6 "awards": { wins: 1, nominations: 1 } 7 }, 8 { 9 "_id": 2, 10 "genres": [ "Animation", "Adventure", "Family" ], 11 "title": "how to train your dragon", 12 "awards": { "wins": 32, "nominations": 51 }, 13 } 14 ]) { acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
Atlas Search 인덱스 만들기
개요
이 섹션에서는 sample_mflix.movies
컬렉션의 title
, released
, awards.wins
필드에 대해 이러한 필드 관련 쿼리를 실행하고 이러한 필드를 기준으로 결과를 정렬하기 위한 Atlas Search 인덱스를 만듭니다.
이 섹션에서는 sample_mflix.movies
컬렉션의 title
필드에 Atlas Search 인덱스를 생성하여 이 필드에 대해 쿼리를 실행하고 이 필드를 기준으로 결과를 정렬합니다.
절차
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱스 구성을 시작합니다.
페이지에서 다음 항목을 선택한 후 Next를 클릭합니다.
Search Type | Atlas Search 인덱스 유형을 선택합니다. |
Index Name and Data Source | 다음 정보를 지정합니다.
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
인덱스 정의를 지정합니다.
인덱스 정의는 다음과 같습니다.
필드별로 결과를 쿼리하고 정렬하기 위해
awards.wins
필드를 숫자 유형으로 인덱싱합니다.필드별로 결과를 쿼리하고 정렬하기 위해
released
필드를 날짜 유형으로 인덱싱합니다.title
필드를 인덱싱하고 검색하기 위한 키워드 분석기를 지정하고title
필드를 다음의 유형으로 인덱싱합니다.Atlas UI에서 Atlas Search Visual Editor 또는 Atlas Search JSON Editor를 사용하여 인덱싱할 수 있습니다.
Refine Your Index를 클릭합니다.
Index Configurations 섹션에서 Dynamic Mapping을 비활성화하도록 토글합니다.
Field Mappings 섹션에서 Add Field을 클릭하여 Add Field Mapping 창을 표시합니다.
Customized Configuration를 클릭합니다.
다음 필드에 대해 한 번에 하나씩 해당 드롭다운에서 필드 이름과 데이터 유형을 선택하고, 속성이 있는 경우 속성을 구성하거나 기본값을 적용한 다음 Add를 클릭합니다.
필드 이름데이터 유형속성awards.wins
번호
기본값을 적용합니다.
released
날짜
기본값을 적용합니다.
title
Token
기본값을 적용합니다.
title
문자열
Index Analyzer 드롭다운과 Search Analyzer 드롭다운에서 모두
lucene.keyword
를 선택합니다.
기본 인덱스 정의를 다음 정의로 바꿉니다.
{ "mappings": { "dynamic": false, "fields": { "awards": { "dynamic": false, "fields": { "wins": [ { "type": "number" } ] }, "type": "document" }, "released": [ { "type": "date" } ], "title": [{ "type": "token" }, { "type": "string", "analyzer": "lucene.keyword", "searchAnalyzer": "lucene.keyword" }] } } } Next를 클릭합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱스 구성을 시작합니다.
페이지에서 다음 항목을 선택한 후 Next를 클릭합니다.
Search Type | Atlas Search 인덱스 유형을 선택합니다. |
Index Name and Data Source | 다음 정보를 지정합니다.
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
Atlas Search 인덱스를 정의합니다.
다음 인덱스 정의는 title
필드를 다음 유형으로 인덱싱합니다.
Atlas 사용자 인터페이스에서 Atlas Search Visual Editor 또는 Atlas Search JSON Editor를 사용하여 인덱스를 생성할 수 있습니다.
Refine Your Index를 클릭합니다.
Index Configurations 섹션에서 Dynamic Mapping을 비활성화하도록 토글합니다.
Field Mappings 섹션에서 Add Field을 클릭하여 Add Field Mapping 창을 표시합니다.
Customized Configuration를 클릭합니다.
Field Name 드롭다운 메뉴에서
title
을(를) 선택합니다.Data Type 드롭다운 메뉴에서 Token을(를) 선택합니다.
Token Properties 을 확장하고 Normalizer 드롭다운에서
lowercase
을 선택합니다.Add를 클릭합니다.
d 및 e 단계를 반복합니다.
Data Type 드롭다운 메뉴에서 String을(를) 선택합니다.
Add를 클릭합니다.
기본 인덱스 정의를 다음 정의로 바꿉니다.
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "title": [{ 6 "type": "token", 7 "normalizer": "lowercase" 8 },{ 9 "type": "string" 10 }] 11 } 12 } 13 } Next를 클릭합니다.
검색 결과 정렬
➤ 언어 선택 드롭다운 메뉴를 사용하여 이 섹션에 있는 예시의 언어를 설정합니다.
여러 가지 방법으로 검색 결과를 정렬할 수 있습니다. 이 섹션에서는 Atlas 클러스터에 연결한 다음 sample_mflix.movies
collection의 인덱싱된 필드에 대해 샘플 쿼리를 실행합니다.
숫자 정렬
샘플 쿼리의 $search
단계에서는 sort
옵션을 사용하여 인덱싱된 번호 필드를 기준으로 Atlas Search 결과를 정렬합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
[ { "$search": { "index": "sort-tutorial", "range": { "path": "awards.wins", "gte": 10 }, "sort": { "awards.wins": -1, } } } ]
SCORE: 1 _id: "573a13d5f29313caabd9cae7" fullplot: "Based on an incredible true story of one man's fight for survival and …" imdb: Object ... year: 2013 ... awards: Object wins: 267 ... ... SCORE: 1 _id: "573a13c7f29313caabd74a4d" fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…" imdb: Object ... year: 2013 ... awards: Object wins: 231 ... ... SCORE: 1 _id: "573a13cbf29313caabd808d2" fullplot: "Dr. Ryan Stone (Sandra Bullock) is a brilliant medical engineer on her…" imdb: Object ... year: 2013 ... awards: Object wins: 231 ... ... SCORE: 1 _id: “573a13dff29313caabdb7adb”" fullplot: "Actor Riggan Thomson is most famous for his movie role from over twent…" imdb: Object ... year: 2014 ... awards: Object wins: 210 ... ... SCORE: 1 _id: "573a13bef29313caabd5c06c" plot: "The life of Mason, from early childhood to his arrival at college." imdb: Object ... runtime: 165 ... awards: Object wins: 185 ... ... SCORE: 1 _id: "573a139ef29313caabcfbd6a" fullplot: "While Frodo & Sam continue to approach Mount Doom to destroy the One R…" imdb: Object ... year: 2003 ... awards: Object wins: 175 ... ... SCORE: 1 _id: "573a13b5f29313caabd447f5" plot: "In rural Texas, welder and hunter Llewelyn Moss discovers the remains …" imdb: Object ... year: 2007 ... awards: Object wins: 172 ... ... SCORE: 1 _id: "573a13c3f29313caabd68d9f" plot: "On a fall night in 2003, Harvard undergrad and computer programming ge…" imdb: Object ... year: 2010 ... awards: Object wins: 171 ... ... SCORE: 1 _id: "573a13c5f29313caabd6ee61" fullplot: "Dom Cobb is a skilled thief, the absolute best in the dangerous art of…" imdb: Object ... year: 2010 ... awards: Object wins: 162 ... ... SCORE: 1 _id: "573a13bdf29313caabd58fd3" plot: "The story of Jamal Malik, an 18 year-old orphan from the slums of Mumb…" imdb: Object ... year: 2008 ... awards: Object wins: 161 ... ...
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
mongosh
에서 클러스터에 연결합니다.
터미널 창에서 mongosh
를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh
를 통한 연결을 참조하세요.
sample_mflix
데이터베이스를 사용합니다.
mongosh
프롬프트에서 다음 명령을 실행합니다.
use sample_mflix
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
단계를 사용하여awards.wins
필드를 검색하고 결과를 내림차순으로 정렬합니다.$limit
단계는 출력을5
결과로만 제한합니다.title
과awards.wins
를 제외한 모든 필드를 제외하려면$project
단계를 수행합니다.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "index": "sort-tutorial", 5 "range": { 6 "path": "awards.wins", 7 "gte": 10 8 }, 9 "sort": { 10 "awards.wins": -1, 11 } 12 } 13 }, 14 { 15 $limit: 5 16 }, 17 { 18 "$project": { 19 "_id": 0, 20 "title": 1, 21 "awards.wins": 1 22 } 23 } 24 ])
[ { title: '12 Years a Slave', awards: { wins: 267 } }, { title: 'Gravity', awards: { wins: 231 } }, { title: 'Gravity', awards: { wins: 231 } }, { title: 'Birdman: Or (The Unexpected Virtue of Ignorance)', awards: { wins: 210 } }, { title: 'Boyhood', awards: { wins: 185 } } ]
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
단계를 사용하여awards.wins
필드를 검색하고 결과를 내림차순으로 정렬합니다.$limit
단계는 출력을5
결과로만 제한합니다.title
과awards.wins
를 제외한 모든 필드를 제외하려면$project
단계를 수행합니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
파이프라인 단계쿼리$search
{ index: "sort-tutorial", "range": { "path": "awards.wins", "gte": 10 }, "sort": { "awards.wins": -1, } } $limit
5 $project
{ title: 1, released: 1, year: 1 } Auto Preview를 활성화한 경우 MongoDB Compass는
$limit
파이프라인 단계 옆에 다음 문서를 표시합니다.[ { title: '12 Years a Slave', awards: { wins: 267 } }, { title: 'Gravity', awards: { wins: 231 } }, { title: 'Gravity', awards: { wins: 231 } }, { title: 'Birdman: Or (The Unexpected Virtue of Ignorance)', awards: { wins: 210 } }, { title: 'Boyhood', awards: { wins: 185 } } ]
Program.cs
파일에 쿼리를 생성합니다.
Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class SortByNumbers 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define search options 23 var searchOptions = new SearchOptions<MovieDocument>() 24 { 25 Sort = Builders<MovieDocument>.Sort.Descending(movies => movies.Awards.Wins), 26 IndexName = "sort-tutorial" 27 }; 28 29 // define and run pipeline 30 var results = moviesCollection.Aggregate() 31 .Search( 32 Builders<MovieDocument>.Search.Range(movie => movie.Awards.Wins, SearchRangeBuilder.Gte(10)), searchOptions) 33 .Project<MovieDocument>(Builders<MovieDocument>.Projection 34 .Exclude(movie => movie.Id) 35 .Include(movie => movie.Title) 36 .Include(movie => movie.Awards.Wins)) 37 .Limit(5) 38 .ToList(); 39 40 // print results 41 foreach (var movie in results) 42 { 43 Console.WriteLine(movie.ToJson()); 44 } 45 } 46 } 47 48 [ ]49 public class MovieDocument 50 { 51 [ ]52 public ObjectId Id { get; set; } 53 public string Title { get; set; } 54 public Award Awards { get; set; } 55 } 56 57 public class Award 58 { 59 [ ]60 public int Wins { get; set; } 61 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
Program.cs
파일을 컴파일하고 실행합니다.
dotnet run Program.cs
{ "title" : "12 Years a Slave", "awards" : { "wins" : 267 } } { "title" : "Gravity", "awards" : { "wins" : 231 } } { "title" : "Gravity", "awards" : { "wins" : 231 } } { "title" : "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards" : { "wins" : 210 } } { "title" : "Boyhood", "awards" : { "wins" : 185 } }
다음 코드를 복사하여 sort-by-numbers.go
파일에 붙여넣습니다.
이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/bson" 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func main() { 13 // connect to your Atlas cluster 14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 15 if err != nil { 16 panic(err) 17 } 18 defer client.Disconnect(context.TODO()) 19 20 // set namespace 21 collection := client.Database("sample_mflix").Collection("movies") 22 23 // define pipeline stages 24 searchStage := bson.D{{"$search", bson.D{ 25 {"index", "sort-tutorial"}, 26 {"range", bson.D{ 27 {"path", "awards.wins"}, 28 {"gte", 10}, 29 }}, 30 {"sort", bson.D{{"awards.wins", -1}}}, 31 }}} 32 limitStage := bson.D{{"$limit", 5}} 33 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"awards.wins", 1}, {"_id", 0}}}} 34 35 // run pipeline 36 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 37 if err != nil { 38 panic(err) 39 } 40 41 // print results 42 var results []bson.D 43 if err = cursor.All(context.TODO(), &results); err != nil { 44 panic(err) 45 } 46 for _, result := range results { 47 fmt.Println(result) 48 } 49 }
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
SortByNumbers.java
이라는 파일을 만듭니다.다음 코드를 복사하여
SortByNumbers.java
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import java.util.Arrays; 2 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.excludeId; 6 import static com.mongodb.client.model.Projections.fields; 7 import static com.mongodb.client.model.Projections.include; 8 import com.mongodb.client.MongoClient; 9 import com.mongodb.client.MongoClients; 10 import com.mongodb.client.MongoCollection; 11 import com.mongodb.client.MongoDatabase; 12 import org.bson.Document; 13 14 public class SortByNumbers { 15 public static void main( String[] args ) { 16 // define query 17 Document agg = 18 new Document("$search", 19 new Document("index", "sort-tutorial") 20 .append("range", 21 new Document("path", "awards.wins") 22 .append("gte", 10L)) 23 .append("sort", 24 new Document("awards.wins", -1L))); 25 26 // specify connection 27 String uri = "<connection-string>"; 28 29 // establish connection and set namespace 30 try (MongoClient mongoClient = MongoClients.create(uri)) { 31 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 32 MongoCollection<Document> collection = database.getCollection("movies"); 33 34 // run query and print results 35 collection.aggregate(Arrays.asList(agg, 36 limit(5), 37 project(fields(excludeId(), include("title"), include("awards.wins"))))) 38 .forEach(doc -> System.out.println(doc.toJson())); 39 } 40 } 41 } 참고
Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.
package com.mongodb.drivers; 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.SortByNumbers.java
파일을 컴파일하고 실행합니다.javac SortByNumbers.java java SortByNumbers {"title": "12 Years a Slave", "awards": {"wins": 267}} {"title": "Gravity", "awards": {"wins": 231}} {"title": "Gravity", "awards": {"wins": 231}} {"title": "Birdman: Or (The Unexpected Virtue of Ignorance)", "awards": {"wins": 210}} {"title": "Boyhood", "awards": {"wins": 185}}
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
SortByNumbers.kt
이라는 파일을 만듭니다.다음 코드를 복사하여
SortByNumbers.kt
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
AggregateFlow
인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 15 runBlocking { 16 // define query 17 val agg = Document( 18 "\$search", 19 Document("index", "sort-tutorial") 20 .append( 21 "range", 22 Document("path", "awards.wins") 23 .append("gte", 10L) 24 ) 25 .append( 26 "sort", 27 Document("awards.wins", -1L) 28 ) 29 ) 30 31 // run query and print results 32 val resultsFlow = collection.aggregate<Document>( 33 listOf( 34 agg, 35 limit(5), 36 project(fields( 37 excludeId(), 38 include("title", "awards.wins") 39 )) 40 ) 41 ) 42 resultsFlow.collect { println(it) } 43 } 44 mongoClient.close() 45 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.SortByNumbers.kt
파일을 실행합니다.IDE에서
SortByNumbers.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{title=12 Years a Slave, awards=Document{{wins=267}}}} Document{{title=Gravity, awards=Document{{wins=231}}}} Document{{title=Gravity, awards=Document{{wins=231}}}} Document{{title=Birdman: Or (The Unexpected Virtue of Ignorance), awards=Document{{wins=210}}}} Document{{title=Boyhood, awards=Document{{wins=185}}}}
다음 코드를 복사하여 sort-by-numbers.js
파일에 붙여넣습니다.
이 코드 예시에서는 다음 작업을 수행합니다:
MongoDB의 Node.js 드라이버인
mongodb
를 가져옵니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployments connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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 = [ 19 { 20 '$search': { 21 'index': 'sort-tutorial', 22 'range': { 23 'path': 'awards.wins', 24 'gte': 10 25 }, 26 'sort': { 27 'awards.wins': -1 28 } 29 } 30 }, { 31 '$limit': 5 32 }, { 33 '$project': { 34 '_id': 0, 35 'title': 1, 36 'awards.wins': 1 37 } 38 } 39 ]; 40 41 // run pipeline 42 const result = await coll.aggregate(agg); 43 44 // print results 45 await result.forEach((doc) => console.log(doc)); 46 47 } finally { 48 await client.close(); 49 } 50 } 51 run().catch(console.dir);
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
node sort-by-numbers.js
{ title: '12 Years a Slave', awards: { wins: 267 } } { title: 'Gravity', awards: { wins: 231 } } { title: 'Gravity', awards: { wins: 231 } } { title: 'Birdman: Or (The Unexpected Virtue of Ignorance)', awards: { wins: 210 } } { title: 'Boyhood', awards: { wins: 185 } }
다음 코드를 복사하여 sort-by-numbers.py
파일에 붙여넣습니다.
다음 코드 예제에서는:
pymongo
, MongoDB의 Python 드라이버 및dns
모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여pymongo
를Atlas
에 연결하는 데 필요합니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음 쿼리는 숫자 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 범위 연산자를 사용하여 10개 이상의 상을 수상한 영화를 검색한 다음 숫자 필드 값을 기준으로 결과를 내림차순으로 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$search': { 10 'index': 'sort-tutorial', 11 'range': { 12 'path': 'awards.wins', 13 'gte': 10 14 }, 15 'sort': { 16 'awards.wins': -1 17 } 18 } 19 }, { 20 '$limit': 5 21 }, { 22 '$project': {'_id': 0, 'title': 1, 'awards.wins': 1 23 } 24 } 25 ] 26 27 # run pipeline 28 result = client['sample_mflix']['movies'].aggregate(pipeline) 29 30 # print results 31 for i in result: 32 print(i)
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
python sort-by-numbers.py
{'title': '12 Years a Slave', 'awards': {'wins': 267}} {'title': 'Gravity', 'awards': {'wins': 231}} {'title': 'Gravity', 'awards': {'wins': 231}} {'title': 'Birdman: Or (The Unexpected Virtue of Ignorance)', 'awards': {'wins': 210}} {'title': 'Boyhood', 'awards': {'wins': 185}}
날짜 정렬하기
샘플 쿼리의 $search
단계에서는 sort
옵션을 사용하여 인덱싱된 날짜 필드를 기준으로 Atlas Search 결과를 정렬합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱싱된 날짜 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
[ { $search: { "index": "sort-tutorial", "compound": { "filter": [{ "wildcard": { "query": "Summer*", "path": "title" } }], "must": [{ "near": { "pivot": 13149000000, "path": "released", "origin": ISODate("2014-04-18T00:00:00.000+00:00") } }] }, "sort": { "released": -1, "title": 1 } } } ]
SCORE: 0.348105788230896 _id: "573a13f0f29313caabddaf7a" countries: Array runtime: 104 cast: Array ... title: "Summer Nights" ... released: 2015-01-28T00:00:00.000+00:00 ... SCORE: 0.5917375683784485 _id: "573a13e6f29313caabdc673b" plot: "25-year-old Iiris and Karoliina have been best friends since childhood…" genres: Array runtime: 90 ... title: "Summertime" ... released: 2014-08-01T00:00:00.000+00:00 ... SCORE: 0.9934720396995544 _id: "573a13eff29313caabdd760c" plot: "Erik Sparrow is one of the lucky ones. He's got a good job. He's in a …" genres: Array runtime: 86 ... title: "Summer of Blood" ... released: 2014-04-17T00:00:00.000+00:00 ... SCORE: 0.15982933342456818 _id: "573a13cff29313caabd8ab74" plot: "The story of an adult and a teenage couple during a brief summer holid…" genres: Array countries: Array ... title: "Summer Games" ... released: 2012-02-08T00:00:00.000+00:00 ... SCORE: 0.13038821518421173 _id: "573a13cef29313caabd87f4e" plot: "Summer of Goliath is a documentary/fiction hybrid that narrates variou…" genres: Array runtime: 78 ... title: "Summer of Goliath" ... released: 2011-07-08T00:00:00.000+00:00 ... SCORE: 0.08124520629644394 _id: "573a13c7f29313caabd7608d" plot: "A student tries to fix a problem he accidentally caused in OZ, a digit…" genres: Array runtime: 114 ... title: "Summer Wars" ... released: 2009-08-01T00:00:00.000+00:00 SCORE: 0.0711759403347969 _id: "573a13bbf29313caabd54ee6" plot: "The life of a public school epitomized by disobedient student Jonah Ta…" genres: Array runtime: 30 ... title: "Summer Heights High" ... released: 2008-11-09T00:00:00.000+00:00 ... SCORE: 0.06951779872179031 _id: "573a13bff29313caabd5f935" plot: "On his spring break at the seaside, with his wife and his four year ol…" genres: Array runtime: 102 ... title: "Summer Holiday" ... released: 2008-09-19T00:00:00.000+00:00 ... SCORE: 0.05834990739822388 _id: "573a13c0f29313caabd628ac" plot: "Kochi Uehara is a fourth grade student living in the suburb of Tokyo. …" genres: Array runtime: 138 ... title: "Summer Days with Coo" ... released: 2007-07-28T00:00:00.000+00:00 ... SCORE: 0.056174591183662415 _id: "573a13b8f29313caabd4c1d0" fullplot: "Country girl Yu Hong leaves her village, her family and her lover to s…" genres: Array runtime: 158 ... title: "Summer Palace" ... released: 2007-04-18T00:00:00.000+00:00 ...
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
mongosh
에서 클러스터에 연결합니다.
터미널 창에서 mongosh
를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh
를 통한 연결을 참조하세요.
sample_mflix
데이터베이스를 사용합니다.
mongosh
프롬프트에서 다음 명령을 실행합니다.
use sample_mflix
인덱싱된 날짜 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
단계를 사용하여title
과released
필드를 검색한 다음 결과를released
필드를 기준으로 내림차순으로 정렬합니다.$limit
단계는 출력을5
결과로만 제한합니다.$project
단계로 이동합니다:title
와released
이외의 모든 필드를 제외합니다.score
(이)라는 필드를 추가합니다.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "index": "sort-tutorial", 5 "compound": { 6 "filter": [{ 7 "wildcard": { 8 "query": "Summer*", 9 "path": "title" 10 } 11 }], 12 "must": [{ 13 "near": { 14 "pivot": 13149000000, 15 "path": "released", 16 "origin": ISODate("2014-04-18T00:00:00.000+00:00") 17 } 18 }] 19 }, 20 "sort": { 21 "released": -1 22 } 23 } 24 }, 25 { 26 $limit: 5 27 }, 28 { 29 $project: { 30 "_id": 0, 31 "title": 1, 32 "released": 1, 33 "score": { 34 "$meta": "searchScore" 35 } 36 } 37 }])
[ { title: 'Summer Nights', released: ISODate("2015-01-28T00:00:00.000Z"), score: 0.348105788230896 }, { title: 'Summertime', released: ISODate("2014-08-01T00:00:00.000Z"), score: 0.5917375683784485 }, { title: 'Summer of Blood', released: ISODate("2014-04-17T00:00:00.000Z"), score: 0.9934720396995544 }, { title: 'Summer Games', released: ISODate("2012-02-08T00:00:00.000Z"), score: 0.15982933342456818 }, { title: 'Summer of Goliath', released: ISODate("2011-07-08T00:00:00.000Z"), score: 0.13038821518421173 } ]
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 매우 빠르게 정렬합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
단계를 사용하여title
과released
필드를 검색한 다음 결과를released
필드를 기준으로 내림차순으로 정렬합니다.$limit
단계는 출력을5
결과로만 제한합니다.$project
단계로 이동합니다:title
와released
이외의 모든 필드를 제외합니다.score
(이)라는 필드를 추가합니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
파이프라인 단계쿼리$search
{ "index": "sort-tutorial", "compound": { "filter": [{ "wildcard": { "query": "Summer*", "path": "title" } }], "must": [{ "near": { "pivot": 13149000000, "path": "released", "origin": ISODate("2014-04-18T00:00:00.000+00:00") } }] }, "sort": { "released": -1 } } $limit
5 $project
{ _id: 0, title: 1, released: 1, score: { $meta: "searchScore" } } Auto Preview를 활성화한 경우 MongoDB Compass는
$limit
파이프라인 단계 옆에 다음 문서를 표시합니다.{ title: 'Summer Nights', released: 2015-01-28T00:00:00.000+00:00, score: 0.348105788230896 }, { title: 'Summertime', released: 2014-08-01T00:00:00.000+00:00, score: 0.5917375683784485 }, { title: 'Summer of Blood', released: 2014-04-17T00:00:00.000+00:00, score: 0.9934720396995544 }, { title: 'Summer Games', released: 2012-02-08T00:00:00.000+00:00, score: 0.15982933342456818 }, { title: 'Summer of Goliath', released: 2011-07-08T00:00:00.000+00:00, score: 0.13038821518421173 }
Program.cs
파일에 쿼리를 생성합니다.
Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class SortByStrings 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 23 // declare data for compound query 24 var originDate = new DateTime(2014, 04, 18, 0, 0, 0, DateTimeKind.Utc); 25 26 // define search options 27 var searchOptions = new SearchOptions<MovieDocument>() 28 { 29 Sort = Builders<MovieDocument>.Sort.Descending(movie => movie.Released), 30 IndexName = "sort-tutorial" 31 }; 32 33 // define and run pipeline 34 var results = moviesCollection.Aggregate() 35 .Search(Builders<MovieDocument>.Search.Compound() 36 .Filter(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Summer*")) 37 .Must(Builders<MovieDocument>.Search.Near(movie => movie.Released, originDate, 13149000000)), searchOptions) 38 .Project<MovieDocument>(Builders<MovieDocument>.Projection 39 .Include(movie => movie.Released) 40 .Include(movie => movie.Title) 41 .Exclude(movie => movie.Id) 42 .MetaSearchScore(movie => movie.Score)) 43 .Limit(5) 44 .ToList(); 45 46 // print results 47 foreach (var movie in results) 48 { 49 Console.WriteLine(movie.ToJson()); 50 } 51 } 52 } 53 54 [ ]55 public class MovieDocument 56 { 57 [ ]58 public ObjectId Id { get; set; } 59 public DateTime Released { get; set; } 60 public string Title { get; set; } 61 public double Score { get; set; } 62 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
Program.cs
파일을 컴파일하고 실행합니다.
dotnet run Program.cs
{ "released" : ISODate("2015-01-28T00:00:00Z"), "title" : "Summer Nights", "score" : 0.348105788230896 } { "released" : ISODate("2014-08-01T00:00:00Z"), "title" : "Summertime", "score" : 0.59173756837844849 } { "released" : ISODate("2014-04-17T00:00:00Z"), "title" : "Summer of Blood", "score" : 0.99347203969955444 } { "released" : ISODate("2014-01-17T00:00:00Z"), "title" : "Summer in February", "score" : 0.62580311298370361 } { "released" : ISODate("2012-02-08T00:00:00Z"), "title" : "Summer Games", "score" : 0.15982933342456818 }
다음 코드를 복사하여 sort-by-date.go
파일에 붙여넣습니다.
이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 package main 2 3 import ( 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 13 func 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": "sort-tutorial", 27 "compound": bson.M{ 28 "filter": bson.A{ 29 bson.M{ 30 "wildcard": bson.D{ 31 {"path", "title"}, 32 {"query", "Summer*"}, 33 }}, 34 }, 35 "must": bson.A{ 36 bson.M{ 37 "near": bson.M{ 38 "path": "released", 39 "origin": time.Date(2014, time.April, 18, 0, 0, 0, 0, time.UTC), 40 "pivot": 13149000000}}, 41 }, 42 }, 43 "sort": bson.D{{"released", -1}}, 44 }}} 45 46 limitStage := bson.D{{"$limit", 5}} 47 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 48 49 // run pipeline 50 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 51 if err != nil { 52 panic(err) 53 } 54 55 // print results 56 var results []bson.D 57 if err = cursor.All(context.TODO(), &results); err != nil { 58 panic(err) 59 } 60 for _, result := range results { 61 fmt.Println(result) 62 } 63 }
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
go run sort-by-date.go
[{title Summer Nights} {released 1422403200000} {score 0.348105788230896}] [{title Summertime} {released 1406851200000} {score 0.5917375683784485}] [{title Summer of Blood} {released 1397692800000} {score 0.9934720396995544}] [{title Summer Games} {released 1328659200000} {score 0.15982933342456818}] [{title Summer of Goliath} {released 1310083200000} {score 0.13038821518421173}]
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
SortByDate.java
이라는 파일을 만듭니다.다음 코드를 복사하여
SortByDate.java
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 import java.time.Instant; 14 import java.util.Date; 15 16 public class SortByDate { 17 public static void main( String[] args ) { 18 // define query 19 Document agg = 20 new Document("$search", 21 new Document("index", "sort-tutorial") 22 .append("compound", 23 new Document("filter", Arrays.asList(new Document("wildcard", 24 new Document("query", "Summer*") 25 .append("path", "title")))) 26 .append("must", Arrays.asList(new Document("near", 27 new Document("pivot", 13149000000L) 28 .append("path", "released") 29 .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00"))))))) 30 .append("sort", new Document("released", -1))); 31 32 // specify connection 33 String uri = "<connection-string>"; 34 35 // establish connection and set namespace 36 try (MongoClient mongoClient = MongoClients.create(uri)) { 37 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 38 MongoCollection<Document> collection = database.getCollection("movies"); 39 // run query and print results 40 collection.aggregate(Arrays.asList(agg, 41 limit(5), 42 project(fields(exclude("_id"), include("title"), include("released"), computed("score", new Document("$meta", "searchScore")))))) 43 .forEach(doc -> System.out.println(doc.toJson())); 44 } 45 } 46 } 참고
Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.
package com.mongodb.drivers; 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.SortDateForSpeed.java
파일을 컴파일하고 실행합니다.javac SortByDate.java java SortByDate {"title": "Summer Nights", "released": {"$date": "2015-01-28T00:00:00Z"}, "score": 0.348105788230896} {"title": "Summertime", "released": {"$date": "2014-08-01T00:00:00Z"}, "score": 0.5917375683784485} {"title": "Summer of Blood", "released": {"$date": "2014-04-17T00:00:00Z"}, "score": 0.9934720396995544} {"title": "Summer Games", "released": {"$date": "2012-02-08T00:00:00Z"}, "score": 0.15982933342456818} {"title": "Summer of Goliath", "released": {"$date": "2011-07-08T00:00:00Z"}, "score": 0.13038821518421173}
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
SortByDate.kt
이라는 파일을 만듭니다.다음 코드를 복사하여
SortByDate.kt
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
AggregateFlow
인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 import java.time.Instant 8 import java.util.* 9 10 fun main() { 11 // establish connection and set namespace 12 val uri = "<connection-string>" 13 val mongoClient = MongoClient.create(uri) 14 val database = mongoClient.getDatabase("sample_mflix") 15 val collection = database.getCollection<Document>("movies") 16 17 runBlocking { 18 // define query 19 val agg = Document( 20 "\$search", 21 Document("index", "sort-tutorial") 22 .append( 23 "compound", 24 Document( 25 "filter", listOf( 26 Document( 27 "wildcard", 28 Document("query", "Summer*") 29 .append("path", "title") 30 ) 31 ) 32 ) 33 .append( 34 "must", listOf( 35 Document( 36 "near", 37 Document("pivot", 13149000000L) 38 .append("path", "released") 39 .append("origin", Date.from(Instant.parse("2014-04-18T00:00:00.000+00:00"))) 40 ) 41 ) 42 ) 43 ) 44 .append("sort", Document("released", -1)) 45 ) 46 47 // run query and print results 48 val resultsFlow = collection.aggregate<Document>( 49 listOf( 50 agg, 51 limit(5), 52 project(fields( 53 excludeId(), 54 include("title", "released"), 55 computed("score", Document("\$meta", "searchScore")) 56 )) 57 ) 58 ) 59 resultsFlow.collect { println(it) } 60 } 61 mongoClient.close() 62 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.SortByDate.kt
파일을 실행합니다.IDE에서
SortByDate.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{title=Summer Nights, released=Tue Jan 27 19:00:00 EST 2015, score=0.348105788230896}} Document{{title=Summertime, released=Thu Jul 31 20:00:00 EDT 2014, score=0.5917375683784485}} Document{{title=Summer of Blood, released=Wed Apr 16 20:00:00 EDT 2014, score=0.9934720396995544}} Document{{title=Summer Games, released=Tue Feb 07 19:00:00 EST 2012, score=0.15982933342456818}} Document{{title=Summer of Goliath, released=Thu Jul 07 20:00:00 EDT 2011, score=0.13038821518421173}}
다음 코드를 복사하여 sort-by-date.js
파일에 붙여넣습니다.
이 코드 예시에서는 다음 작업을 수행합니다:
MongoDB의 Node.js 드라이버인
mongodb
를 가져옵니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployments connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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 = [ 19 {$search: { 20 index: "sort-tutorial", 21 compound: { 22 filter: {wildcard: {query: "Summer*", path: "title"}}, 23 must: [{near: {path: "released", origin: new Date("2014-04-18T00:00:00.000Z"), pivot: 13149000000}}] 24 }, 25 sort: { released: -1 } 26 }}, 27 {$limit: 5}, 28 {$project: {_id: 0, title: 1, released: 1, score: {$meta: "searchScore"}}} 29 ]; 30 31 // run pipeline 32 const result = await coll.aggregate(agg); 33 34 // print results 35 await result.forEach((doc) => console.log(doc)); 36 37 } finally { 38 await client.close(); 39 } 40 } 41 run().catch(console.dir);
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
node sort-by-date.js
{ title: 'Summer Nights', released: 2015-01-28T00:00:00.000Z, score: 0.348105788230896 } { title: 'Summertime', released: 2014-08-01T00:00:00.000Z, score: 0.5917375683784485 } { title: 'Summer of Blood', released: 2014-04-17T00:00:00.000Z, score: 0.9934720396995544 } { title: 'Summer Games', released: 2012-02-08T00:00:00.000Z, score: 0.15982933342456818 } { title: 'Summer of Goliath', released: 2011-07-08T00:00:00.000Z, score: 0.13038821518421173 }
다음 코드를 복사하여 sort-by-date.py
파일에 붙여넣습니다.
다음 코드 예제에서는:
pymongo
, MongoDB의 Python 드라이버 및dns
모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여pymongo
를Atlas
에 연결하는 데 필요합니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음 쿼리는 복합 쿼리를 실행하고 날짜 필드를 기준으로 결과를 정렬하는 방법을 보여 줍니다. 다음 연산자를 사용합니다.
와일드카드 연산자를 사용하여
Summer
로 시작하는 영화 제목을 검색합니다.근사(near) 연산자를 입력해 2014년 4월 18일 전후로 약 5개월 안에 개봉한 영화를 검색할 수 있습니다.
참고
날짜 필드에
pivot
를 사용하는 경우 해당 측정 단위는 밀리초입니다. Atlas Search는 날짜 필드가 지정된 날짜와 얼마나 가까운지에 따라 각 문서의 점수를 계산합니다. 자세한 내용은 근사를 참조하세요.
쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import datetime 2 import pymongo 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient('<connection-string>') 6 7 # define pipeline 8 pipeline = [ 9 {'$search': { 10 'index': 'sort-tutorial', 11 'compound': { 12 'filter': {'wildcard': {'query': 'Summer*', 'path': 'title'}}, 13 'must': {'near': { 14 "path": "released", 15 "origin": datetime.datetime(2014, 4, 18, 0, 0, 0, 0), 16 "pivot": 13149000000 17 }}}, 18 'sort': { 'released': -1 }}}, 19 {'$limit': 5}, 20 {'$project': {'_id': 0, 'title': 1, 'released': 1, 'score': {'$meta': 'searchScore'}}} 21 ] 22 23 # run pipeline 24 result = client['sample_mflix']['movies'].aggregate(pipeline) 25 26 # print results 27 for i in result: 28 print(i)
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
python sort-date-for-speed.py
{'title': 'Summer Nights', 'released': datetime.datetime(2015, 1, 28, 0, 0), 'score': 0.348105788230896} {'title': 'Summertime', 'released': datetime.datetime(2014, 8, 1, 0, 0), 'score': 0.5917375683784485} {'title': 'Summer of Blood', 'released': datetime.datetime(2014, 4, 17, 0, 0), 'score': 0.9934720396995544} {'title': 'Summer Games', 'released': datetime.datetime(2012, 2, 8, 0, 0), 'score': 0.15982933342456818} {'title': 'Summer of Goliath', 'released': datetime.datetime(2011, 7, 8, 0, 0), 'score': 0.13038821518421173}
문자열 정렬하기
샘플 쿼리의 $search
단계에서는 sort
옵션을 사용하여 인덱싱된 문자열 필드를 기준으로 Atlas Search 결과를 정렬합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱싱된 문자열 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다. Prance
또는 Prince
로 시작하는 제목을 검색하고 title
필드를 기준으로 오름차순으로 결과를 정렬합니다.
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
[ { $search: { "index": "sort-tutorial", "compound": { "should": [{ "wildcard": { "query": ["Prance*"], "path": "title", "allowAnalyzedField": true } }, { "wildcard": { "query": ["Prince*"], "path": "title", "allowAnalyzedField": true } }] }, "sort": { "title": 1 } } } ]
SCORE: 1 _id: "573a1398f29313caabceb98e" plot: "A farm girl nurses a wounded reindeer she believes is one of Santa's, …" genres: Array runtime: 103 ... title: "Prancer" ... SCORE: 1 _id: "573a13a5f29313caabd14f54" plot: "Preteen brothers from a broken marriage live with their mother, Denise…" genres: Array runtime: 91 ... title: "Prancer Returns" ... SCORE: 1 _id: "573a13f5f29313caabde3755" plot: "A troubled teenager attempts to conquer the love of his life by becomi…" genres: Array runtime: 78 ... title: "Prince" ... SCORE: 1 _id: "573a13d8f29313caabda665f" fullplot: "Two highway road workers spend the summer of 1988 away from their city…" imdb: Object year: 2013 ... title: "Prince Avalanche" ... SCORE: 1 _id: "573a13bdf29313caabd5898a" plot: "A New York street drama about the lives of immigrants in America seeki…" genres: Array runtime: 70 ... title: "Prince of Broadway" ... SCORE: 1 _id: "573a1398f29313caabcea967" fullplot: "A sinister secret has been kept in the basement of an abandoned Los An…" imdb: Object year: 1987 ... title: "Prince of Darkness" ... SCORE: 1 _id: "573a1393f29313caabcde40d" plot: "An unscrupulous agent for the Borgias suffers a change of heart when a…" genres: Array runtime: 107 ... title: "Princess of Foxes" ... SCORE: 1 _id: "573a13b5f29313caabd43816" plot: "A young fugitive prince and princess must stop a villain who unknowing…" genres: Array runtime: 116 ... title: "Prince of Persia: The Sands of Time" ... SCORE: 1 _id: "573a1397f29313caabce8081" plot: "A New York City narcotics detective reluctantly agrees to cooperate wi…" genres: Array runtime: 167 ... title: "Prince of the City" ... SCORE: 1 _id: "573a13a2f29313caabd0a767" plot: "Six old-style funny silhouetted fairy tales for not so-old-style peopl…" genres: Array runtime: 70 ... title: "Princes and Princesses" ...
Atlas Search 결과에는 Prance
및 Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는 title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에 Prance
다음에 Prince
가 있는 제목을 반환합니다.
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
mongosh
에서 클러스터에 연결합니다.
터미널 창에서 mongosh
를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh
를 통한 연결을 참조하세요.
sample_mflix
데이터베이스를 사용합니다.
mongosh
프롬프트에서 다음 명령을 실행합니다.
use sample_mflix
인덱싱된 문자열 및 날짜 필드에 대해 Atlas Search 쿼리를 실행하고 문자열 필드를 기준으로 오름차순으로 정렬합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다. Prance
또는 Prince
로 시작하는 제목을 검색하고 title
필드를 기준으로 오름차순으로 결과를 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
와일드카드 연산자와 함께
should
절을 사용해title
필드를 검색하여Prance
및Prince
로 시작하는 제목을 검색하려면$search
를 입력합니다. 이 쿼리는 또한 결과가title
필드를 기준으로 오름차순으로 정렬되도록 지정합니다.$limit
단계는 출력을5
결과로만 제한합니다.$project
단계로 이동합니다:title
을 제외한 모든 필드를 제외합니다.score
(이)라는 필드를 추가합니다.
1 db.movies.aggregate([{ 2 $search: { 3 "index": "sort-tutorial", 4 "compound": { 5 "should": [{ 6 "wildcard": { 7 "query": ["Prance*"], 8 "path": "title", 9 "allowAnalyzedField": true 10 } 11 }, 12 { 13 "wildcard": { 14 "query": ["Prince*"], 15 "path": "title", 16 "allowAnalyzedField": true 17 } 18 }] 19 }, 20 "sort": { 21 "title": 1 22 } 23 }}, 24 { 25 $limit: 5 26 }, 27 { 28 $project: { 29 "_id": 0, 30 "title": 1, 31 "score": { "$meta": "searchScore" } 32 } 33 } 34 ])
[ { title: 'Prancer', score: 1 }, { title: 'Prancer Returns', score: 1 }, { title: 'Prince', score: 1 }, { title: 'Prince Avalanche', score: 1 }, { title: 'Prince of Broadway', score: 1 } ]
Atlas Search 결과에는 Prance
및 Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는 title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에 Prance
다음에 Prince
가 있는 제목을 반환합니다.
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다. Prance
또는 Prince
로 시작하는 제목을 검색하고 title
필드를 기준으로 오름차순으로 결과를 정렬합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
와일드카드 연산자와 함께
should
절을 사용해title
필드를 검색하여Prance
및Prince
로 시작하는 제목을 검색하려면$search
를 입력합니다. 이 쿼리는 또한 결과가title
필드를 기준으로 오름차순으로 정렬되도록 지정합니다.$limit
단계는 출력을5
결과로만 제한합니다.$project
단계로 이동합니다:title
을 제외한 모든 필드를 제외합니다.score
(이)라는 필드를 추가합니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
파이프라인 단계쿼리$search
{ index: "sort-tutorial", compound: { should: [{ wildcard: { query: "Prance*", path: 'title', allowAnalyzedField: true }}, { wildcard: { query: "Prince*", path: 'title', allowAnalyzedField: true } }] }, sort: { title: 1 } } $limit
5 $project
{ _id: 0, title: 1, score: { $meta: "searchScore" } } Auto Preview를 활성화한 경우 MongoDB Compass는
$project
파이프라인 단계 옆에 다음 문서를 표시합니다.{ title: 'Prancer', score: 1 }, { title: 'Prancer Returns', score: 1 }, { title: 'Prince', score: 1 }, { title: 'Prince Avalanche', score: 1 }, { title: 'Prince of Boradway', score: 1 } Atlas Search 결과에는
Prance
및Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에Prance
다음에Prince
가 있는 제목을 반환합니다.
Program.cs
파일에 쿼리를 생성합니다.
Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다.
Prance
또는Prince
로 시작하는 제목을 검색하고title
필드를 기준으로 오름차순으로 결과를 정렬합니다.쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class SortByStrings 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define search options 23 var searchOptions = new SearchOptions<MovieDocument>() 24 { 25 Sort = Builders<MovieDocument>.Sort.Ascending(movie => movie.Title), 26 IndexName = "sort-tutorial" 27 }; 28 29 // define and run pipeline 30 var results = moviesCollection.Aggregate() 31 .Search(Builders<MovieDocument>.Search.Compound() 32 .Should(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Prance*", true )) 33 .Should(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Prince*" )), searchOptions) 34 .Project<MovieDocument>(Builders<MovieDocument>.Projection 35 .Include(movie => movie.Title) 36 .Exclude(movie => movie.Id) 37 .MetaSearchScore(movie => movie.Score)) 38 .Limit(5) 39 .ToList(); 40 41 // print results 42 foreach (var movie in results) 43 { 44 Console.WriteLine(movie.ToJson()); 45 } 46 } 47 } 48 49 [ ]50 public class MovieDocument 51 { 52 [ ]53 public ObjectId Id { get; set; } 54 public string Title { get; set; } 55 public double Score { get; set; } 56 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
Program.cs
파일을 컴파일하고 실행합니다.
dotnet run Program.cs
{ "title" : "Prancer", "score" : 1.0 } { "title" : "Prancer Returns", "score" : 1.0 } { "title" : "Prince", "score" : 1.0 } { "title" : "Prince Avalanche", "score" : 1.0 } { "title" : "Prince of Broadway", "score" : 1.0 }
Atlas Search 결과에는 Prance
및 Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는 title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에 Prance
다음에 Prince
가 있는 제목을 반환합니다.
다음 코드를 복사하여 sort-by-strings.go
파일에 붙여넣습니다.
이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다.
Prance
또는Prince
로 시작하는 제목을 검색하고title
필드를 기준으로 오름차순으로 결과를 정렬합니다.쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/bson" 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func main() { 13 // connect to your Atlas cluster 14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 15 if err != nil { 16 panic(err) 17 } 18 defer client.Disconnect(context.TODO()) 19 20 // set namespace 21 collection := client.Database("sample_mflix").Collection("movies") 22 23 // define pipeline stages 24 searchStage := bson.D{{"$search", bson.M{ 25 "index": "sort-tutorial", 26 "compound": bson.M{ 27 "should": bson.A{ 28 bson.M{ 29 "wildcard": bson.D{ 30 {"path", "title"}, 31 {"query", "Prance*"}, 32 {"allowAnalyzedField", true}, 33 }}, 34 bson.M{ 35 "wildcard": bson.D{ 36 {"path", "title"}, 37 {"query", "Prince*"}, 38 {"allowAnalyzedField", true}, 39 }}, 40 }, 41 }, 42 "sort": bson.D{{"title", 1}}, 43 }}} 44 45 limitStage := bson.D{{"$limit", 5}} 46 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 47 48 // run pipeline 49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 50 if err != nil { 51 panic(err) 52 } 53 54 // print results 55 var results []bson.D 56 if err = cursor.All(context.TODO(), &results); err != nil { 57 panic(err) 58 } 59 for _, result := range results { 60 fmt.Println(result) 61 } 62 }
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
go run sort-by-strings.go
[{title Prancer} {score 1}] [{title Prancer Returns} {score 1}] [{title Prince} {score 1}] [{title Prince Avalanche} {score 1}] [{title Prince of Broadway} {score 1}]
Atlas Search 결과에는 Prance
및 Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는 title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에 Prance
다음에 Prince
가 있는 제목을 반환합니다.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
SortByString.java
이라는 파일을 만듭니다.다음 코드를 복사하여
SortByString.java
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다.
Prance
또는Prince
로 시작하는 제목을 검색하고title
필드를 기준으로 오름차순으로 결과를 정렬합니다.쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 import java.util.Date; 14 15 public class SortByString { 16 public static void main( String[] args ) { 17 // define clause 18 List<Document> shouldClause = 19 List.of( 20 new Document( 21 "wildcard", 22 new Document("query", "Prance*") 23 .append("path", "title") 24 .append("allowAnalyzedField", true)), 25 new Document( 26 "wildcard", 27 new Document("query", "Prince*") 28 .append("path", "title") 29 .append("allowAnalyzedField", true))); 30 31 // define query 32 Document agg = 33 new Document( 34 "$search", 35 new Document("index", "sort-tutorial") 36 .append("compound", 37 new Document("should", shouldClause)) 38 .append("sort", new Document("title", 1L))); 39 40 // specify connection 41 String uri = "<connection-string>"; 42 43 // establish connection and set namespace 44 try (MongoClient mongoClient = MongoClients.create(uri)) { 45 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 46 MongoCollection<Document> collection = database.getCollection("movies"); 47 48 // run query and print results 49 collection.aggregate(Arrays.asList(agg, 50 limit(5), 51 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))) 52 .forEach(doc -> System.out.println(doc.toJson())); 53 } 54 } 55 } 참고
Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.
package com.mongodb.drivers; 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.SortByString.java
파일을 컴파일하고 실행합니다.javac SortByString.java java SortByString {"title": "Prancer", "score": 1.0} {"title": "Prancer Returns", "score": 1.0} {"title": "Prince", "score": 1.0} {"title": "Prince Avalanche", "score": 1.0} {"title": "Prince of Broadway", "score": 1.0} Atlas Search 결과에는
Prance
및Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에Prance
다음에Prince
가 있는 제목을 반환합니다.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
SortByString.kt
이라는 파일을 만듭니다.다음 코드를 복사하여
SortByString.kt
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다.
Prance
또는Prince
로 시작하는 제목을 검색하고title
필드를 기준으로 오름차순으로 결과를 정렬합니다.쿼리는 다음 파이프라인 단계를 사용합니다:
AggregateFlow
인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 15 runBlocking { 16 // define clause 17 val shouldClause = listOf( 18 Document("wildcard", Document("query", "Prance*") 19 .append("path", "title") 20 .append("allowAnalyzedField", true)), 21 Document("wildcard", Document("query", "Prince*") 22 .append("path", "title") 23 .append("allowAnalyzedField", true)) 24 ) 25 26 // define query 27 val agg = Document( 28 "\$search", 29 Document("index", "sort-tutorial") 30 .append( 31 "compound", 32 Document("should", shouldClause) 33 ) 34 .append("sort", Document("title", 1L)) 35 ) 36 37 // run query and print results 38 val resultsFlow = collection.aggregate<Document>( 39 listOf( 40 agg, 41 limit(5), 42 project(fields( 43 excludeId(), 44 include("title"), 45 computed("score", Document("\$meta", "searchScore")) 46 )) 47 ) 48 ) 49 resultsFlow.collect { println(it) } 50 } 51 mongoClient.close() 52 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.SortByString.kt
파일을 실행합니다.IDE에서
SortByString.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{title=Prancer, score=1.0}} Document{{title=Prancer Returns, score=1.0}} Document{{title=Prince, score=1.0}} Document{{title=Prince Avalanche, score=1.0}} Document{{title=Prince of Broadway, score=1.0}} Atlas Search 결과에는
Prance
및Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에Prance
다음에Prince
가 있는 제목을 반환합니다.
다음 코드를 복사하여 sort-by-strings.js
파일에 붙여넣습니다.
이 코드 예시에서는 다음 작업을 수행합니다:
MongoDB의 Node.js 드라이버인
mongodb
를 가져옵니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다.
Prance
또는Prince
로 시작하는 제목을 검색하고title
필드를 기준으로 오름차순으로 결과를 정렬합니다.쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployments connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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 = [ 19 { 20 '$search': { 21 'index': 'sort-tutorial', 22 'compound': { 23 'should': [ 24 { 25 'wildcard': { 26 'query': [ 27 'Prance*' 28 ], 29 'path': 'title', 30 'allowAnalyzedField': true 31 } 32 }, { 33 'wildcard': { 34 'query': [ 35 'Prince*' 36 ], 37 'path': 'title', 38 'allowAnalyzedField': true 39 } 40 } 41 ] 42 }, 43 'sort': { 'title': 1 } 44 } 45 }, { 46 '$limit': 5 47 }, { 48 '$project': {'_id': 0, 'title': 1, 'score': {'$meta': 'searchScore'} 49 } 50 } 51 ]; 52 53 // run pipeline 54 const result = await coll.aggregate(agg); 55 56 // print results 57 await result.forEach((doc) => console.log(doc)); 58 59 } finally { 60 await client.close(); 61 } 62 } 63 run().catch(console.dir);
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
node sort-by-strings.js
{ title: 'Prancer', score: 1 } { title: 'Prancer Returns', score: 1 } { title: 'Prince', score: 1 } { title: 'Prince Avalanche', score: 1 } { title: 'Prince of Broadway', score: 1 }
Atlas Search 결과에는 Prance
및 Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는 title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에 Prance
다음에 Prince
가 있는 제목을 반환합니다.
다음 코드를 복사하여 sort-by-strings.py
파일에 붙여넣습니다.
다음 코드 예제에서는:
pymongo
, MongoDB의 Python 드라이버 및dns
모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여pymongo
를Atlas
에 연결하는 데 필요합니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음 쿼리는 문자열 필드를 기준으로 결과를 쿼리하고 정렬하는 방법을 보여 줍니다.
Prance
또는Prince
로 시작하는 제목을 검색하고title
필드를 기준으로 오름차순으로 결과를 정렬합니다.쿼리는 다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'sort-tutorial', 10 'compound': { 11 'should': [{'wildcard': {'query': 'Prance*', 'path': 'title', 'allowAnalyzedField': True}}, 12 {'wildcard': {'query': 'Prince*', 'path': 'title', 'allowAnalyzedField': True}}] 13 }, 14 'sort': { 'title': 1 }}}, 15 {'$limit': 5}, 16 {'$project': {'_id': 0, 'title': 1, 'score': {'$meta': 'searchScore'}}} 17 ] 18 19 # run pipeline 20 result = client['sample_mflix']['movies'].aggregate(pipeline) 21 22 # print results 23 for i in result: 24 print(i)
참고
샘플을 실행하기 전에 <connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
python sort-by-strings.py
{'title': 'Prancer', 'score': 1.0} {'title': 'Prancer Returns', 'score': 1.0} {'title': 'Prince', 'score': 1.0} {'title': 'Prince Avalanche', 'score': 1.0} {'title': 'Prince of Broadway', 'score': 1.0}
Atlas Search 결과에는 Prance
및 Prince
로 시작하는 영화 제목이 있는 문서가 포함되어 있습니다. Atlas Search는 title
필드를 기준으로 문서를 오름차순으로 정렬하기 때문에 Prance
다음에 Prince
가 있는 제목을 반환합니다.
샘플 쿼리의 $search
단계에서는 정렬 옵션을 사용하여 정렬된 필드 값의 대소문자에 관계없이 Atlas Search 결과를 정렬합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
[ { "$search": { "index": "sort-tutorial", "text": { "path": "title", "query": "train", }, "sort": { "title": 1 } } } ]
SCORE: 3.317898988723755 _id: "573a139cf29313caabcf662c" plot: "A train filled with atomic devices threatens to destroy the city of De…" genres: Array runtime: 122 SCORE: 3.317898988723755 _id: "64de50ae2932de4dd3203061" genres: Array title: "atomic train" awards: Object SCORE: 2.228306293487549 _id: "573a13bbf29313caabd52ff4" fullplot: "Long ago up North on the Island of Berk, the young Viking, Hiccup, wan…" imdb: Object year: 2010 SCORE: 2.228306293487549 _id: "64de50da2932de4dd3204393" genres: Array title: "how to train your dragon" awards: Object SCORE: 2.008449077606201 _id: "573a13ccf29313caabd83281" plot: "When Hiccup and Toothless discover an ice cave that is home to hundred…" genres: Array runtime: 102 SCORE: 1.4400973320007324 _id: "573a13b1f29313caabd36490" plot: "The life and times of Howard Zinn: the historian, activist, and author…" genres: Array runtime: 78 SCORE: 2.228306293487549 _id: "573a1394f29313caabce0fb4" plot: "A marshal tries to bring the son of an old friend, an autocratic cattl…" genres: Array runtime: 95 SCORE: 2.8528976440429688 _id: "573a13c8f29313caabd78a6b" plot: "A couple embarks on a journey home for Chinese new year along with 130…" genres: Array runtime: 85 SCORE: 2.502213716506958 _id: "573a13baf29313caabd50811" plot: "Two thugs from the Perth suburb of Midland catch the last train to Fre…" genres: Array runtime: 89 SCORE: 2.502213716506958 _id: "573a13a7f29313caabd1b667" fullplot: "A teacher and a gangster meet by chance in a small town pharmacy. As a…" imdb: Object year: 2002
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
SCORE: 3.317898988723755 _id: "573a139cf29313caabcf662c" plot: "A train filled with atomic devices threatens to destroy the city of De…" genres: Array runtime: 122 SCORE: 2.2382168769836426 _id: "573a13bbf29313caabd52ff4" fullplot: "Long ago up North on the Island of Berk, the young Viking, Hiccup, wan…" imdb: object year: 2010 SCORE: 2.008449077606201 _id: "573a13ccf29313caabd83281" plot: "When Hiccup and Toothless discover an ice cave that is home to hundred…" genres: Array runtime: 102 SCORE: 1.4400973320007324 _id: "573a13b1f29313caabd36490" plot: "The life and times of Howard Zinn: the historian, activist, and author…" genres: Array runtime: 78 SCORE: 2.8528976440429688 _id: "573a13c8f29313caabd78a6b" plot: "A couple embarks on a journey home for Chinese new year along with 130…" genres: Array runtime: 85 SCORE: 2.228306293487549 _id: "573a1394f29313caabce0fb4" plot: "A marshal tries to bring the son of an old friend, an autocratic cattl…" genres: Array runtime: 95 SCORE: 2.502213716506958 _id: "573a13baf29313caabd50811" plot: "Two thugs from the Perth suburb of Midland catch the last train to Fre…" genres: Array runtime: 89 SCORE: 2.502213716506958 _id: "573a13a7f29313caabd1b667" fullplot: "A teacher and a gangster meet by chance in a small town pharmacy. As a…" imdb: Object year: 2002 SCORE: 3.3326687812805176 _id: "573a139af29313caabcef573" plot: "A vengeful New York transit cop decides to steal a trainload of subway…" genres: Array runtime: 110 SCORE: 3.3326687812805176 _id: "573a1398f29313caabceb8f2" plot: "Three stories are connected by a Memphis hotel and the spirit of Elvis…" genres: Array runtime: 110
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
mongosh
에서 클러스터에 연결합니다.
터미널 창에서 mongosh
를 열고 cluster에 연결합니다. 연결에 대한 자세한 지침은 mongosh를 통해 연결을 참조하세요.
인덱싱된 필드에 대해 Atlas Search 쿼리를 실행하고 결과를 정렬합니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
db.movies.aggregate( { "$search": { "index": "case-insensitive-sort", "text": { "path": "title", "query": "train", }, "sort": { "title": 1 } } }, { "$limit": 5 }, { "$project": { "_id": 1, "title": 1, "awards": 1, "score": { $meta: "searchScore" } } } )
[ { _id: ObjectId("573a139cf29313caabcf662c"), title: 'Atomic Train', awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' }, score: 3.317898988723755 }, { _id: ObjectId("64de50ae2932de4dd3203061"), title: 'atomic train', awards: { wins: 1, nominations: 1 }, score: 3.317898988723755 }, { _id: ObjectId("573a13bbf29313caabd52ff4"), title: 'How to Train Your Dragon', awards: { wins: 32, nominations: 51, text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.' }, score: 2.228306293487549 }, { _id: ObjectId("64de50da2932de4dd3204393"), title: 'how to train your dragon', awards: { wins: 32, nominations: 51 }, score: 2.228306293487549 }, { _id: ObjectId("573a13ccf29313caabd83281"), title: 'How to Train Your Dragon 2', awards: { wins: 18, nominations: 52, text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.' }, score: 2.008449077606201 } ]
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
[ { _id: ObjectId("573a139cf29313caabcf662c"), title: 'Atomic Train', awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' }, score: 3.3326687812805176 }, { _id: ObjectId("573a13bbf29313caabd52ff4"), title: 'How to Train Your Dragon', awards: { wins: 32, nominations: 51, text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.' }, score: 2.2382168769836426 }, { _id: ObjectId("573a13ccf29313caabd83281"), title: 'How to Train Your Dragon 2', awards: { wins: 18, nominations: 52, text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.' }, score: 2.0173802375793457 }, { _id: ObjectId("573a13b1f29313caabd36490"), title: "Howard Zinn: You Can't Be Neutral on a Moving Train", awards: { wins: 1, nominations: 0, text: '1 win.' }, score: 1.446497917175293 }, { _id: ObjectId("573a13c8f29313caabd78a6b"), title: 'Last Train Home', awards: { wins: 14, nominations: 9, text: '14 wins & 9 nominations.' }, score: 2.8655927181243896 } ]
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.
컬렉션에 대해 Atlas Search 쿼리를 실행합니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
파이프라인 단계쿼리$search
{ "index": "case-insensitive-sort", "text": { "path": "title", "query": "train", }, "sort": { "title": 1, } } $limit
5
$project
{ "_id": 1, "title": 1, "awards": 1, "score": { $meta: "searchScore" } } Auto Preview를 활성화한 경우 MongoDB Compass는
$project
파이프라인 단계 옆에 다음 문서를 표시합니다._id: ObjectId('573a139cf29313caabcf662c') title: 'Atomic Train' awards: Object score: 3.317898988723755 _id: ObjectId("64de50ae2932de4dd3203061") title: 'atomic train' awards: Object score: 3.317898988723755 _id: ObjectId('573a13bbf29313caabd52ff4') title: 'How to Train Your Dragon' awards: Object score: 2.228306293487549 _id: ObjectId("64de50da2932de4dd3204393"), title: 'how to train your dragon' awards: score: 2.228306293487549 _id: ObjectId('573a13ccf29313caabd83281') title: 'How to Train Your Dragon 2' awards: object score: 2.0173802375793457 결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나
normalizer
을none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다._id: ObjectId('573a139cf29313caabcf662c') title: 'Atomic Train' awards: Object score: 3.317898988723755 _id: ObjectId('573a13bbf29313caabd52ff4') title: 'How to Train Your Dragon' awards: Object score: 2.228306293487549 _id: ObjectId('573a13ccf29313caabd83281') title: 'How to Train Your Dragon 2' awards: score: 2.0173802375793457 _id: ObjectId('573a13b1f29313caabd36490') title: 'Howard Zinn: You Can't Be Neutral on a Moving Train' awards: Object score: 1.446497917175293 _id: ObjectId('573a13c8f29313caabd78a6b') title: 'Last Train Home' awards: Object score: 2.8655927181243896 대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서
normalizer
옵션을none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
쿼리를 복사하여 Program.cs
파일에 붙여넣습니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CaseInsensitiveSort 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 camelCaseConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var yourDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = yourDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define options for search 23 var searchOptions = new SearchOptions<MovieDocument>() { 24 Sort = Builders<MovieDocument>.Sort.Ascending(movie => movie.Title), 25 IndexName = "case-insensitive-sort" 26 }; 27 28 // define and run pipeline 29 var results = moviesCollection.Aggregate() 30 .Search(Builders<MovieDocument>.Search.Text(movie => movie.Title, "train"), searchOptions) 31 .Limit (5) 32 .Project<MovieDocument>(Builders<MovieDocument>.Projection 33 .Include(movie => movie.Id) 34 .Include(movie => movie.Title) 35 .Include(movie => movie.Awards) 36 .MetaSearchScore(movie => movie.Score)) 37 .ToList(); 38 39 // print results 40 foreach (var movie in results) 41 { 42 Console.WriteLine(movie.ToJson()); 43 } 44 } 45 } 46 47 [ ]48 public class MovieDocument 49 { 50 [ ]51 public ObjectId Id { get; set; } 52 public string Title { get; set; } 53 public Award Awards { get; set; } 54 public double Score { get; set; } 55 } 56 57 [ ]58 public class Award 59 { 60 public int Wins { get; set; } 61 public int Nominations { get; set; } 62 }
쿼리에서 <connection-string>
을 바꾼 다음 파일을 저장합니다.
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.
Program.cs
파일을 컴파일하고 실행합니다.
dotnet run case-insensitive-sort.csproj
{ "_id" : ObjectId("573a139cf29313caabcf662c"), "title" : "Atomic Train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035578727722168 } { "_id" : ObjectId("64de50ae2932de4dd3203061"), "title" : "atomic train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035578727722168 } { "_id" : ObjectId("573a13bbf29313caabd52ff4"), "title" : "How to Train Your Dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186923027038574 } { "_id" : ObjectId("64de50da2932de4dd3204393"), "title" : "how to train your dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186923027038574 } { "_id" : ObjectId("573a13ccf29313caabd83281"), "title" : "How to Train Your Dragon 2", "awards" : { "wins" : 18, "nominations" : 52 }, "score" : 1.9997868537902832 }
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
{ "_id" : ObjectId("573a139cf29313caabcf662c"), "title" : "Atomic Train", "awards" : { "wins" : 1, "nominations" : 1 }, "score" : 3.3035225868225098 } { "_id" : ObjectId("573a13bbf29313caabd52ff4"), "title" : "How to Train Your Dragon", "awards" : { "wins" : 32, "nominations" : 51 }, "score" : 2.2186522483825684 } { "_id" : ObjectId("573a13ccf29313caabd83281"), "title" : "How to Train Your Dragon 2", "awards" : { "wins" : 18, "nominations" : 52 }, "score" : 1.9997482299804688 } { "_id" : ObjectId("573a13b1f29313caabd36490"), "title" : "Howard Zinn: You Can't Be Neutral on a Moving Train", "awards" : { "wins" : 1, "nominations" : 0 }, "score" : 1.4338588714599609 } { "_id" : ObjectId("573a13c8f29313caabd78a6b"), "title" : "Last Train Home", "awards" : { "wins" : 14, "nominations" : 9 }, "score" : 2.8405368328094482 }
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
쿼리를 복사하여 case-insensitive-query.go
파일에 붙여넣습니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 7 "go.mongodb.org/mongo-driver/bson" 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func main() { 13 // connect to your Atlas cluster 14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 15 if err != nil { 16 panic(err) 17 } 18 defer client.Disconnect(context.TODO()) 19 20 // set namespace 21 collection := client.Database("sample_mflix").Collection("movies") 22 23 // define pipeline stages 24 searchStage := bson.D{{"$search", bson.M{ 25 "index": "case-insensitive-sort", 26 "text": bson.D{ 27 {"path", "title"}, 28 {"query", "train"}, 29 }, 30 "sort": bson.D{{"title", 1}}, 31 }}} 32 limitStage := bson.D{{"$limit", 5}} 33 projectStage := bson.D{{"$project", bson.D{{"_id", 1}, {"title", 1}, {"awards", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 34 35 // run pipeline 36 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage,projectStage}) 37 if err != nil { 38 panic(err) 39 } 40 41 // print results 42 var results []bson.D 43 if err = cursor.All(context.TODO(), &results); err != nil { 44 panic(err) 45 } 46 for _, result := range results { 47 fmt.Println(result) 48 } 49 }
쿼리에서 다음을 바꾼 다음 파일을 저장합니다.
<connection-string>
(online 14)을(를) Atlas 연결 string 로 변환합니다. 연결 string 에 데이터베이스 사용자의 자격 증명이 포함되어 있는지 확인합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.<database-name>
(21행) 항목에 컬렉션을 추가한 데이터베이스의 이름을 바꿉니다.
명령을 실행하여 컬렉션을 쿼리합니다.
go run case-insensitive-query.go
[{_id ObjectID("573a139cf29313caabcf662c")} {title Atomic Train} {awards [{wins 1} {nominations 1} {text 1 win & 1 nomination.}]} {score 3.317898988723755}] [{_id ObjectId("64de50ae2932de4dd3203061")} {title atomic train} {awards [{wins 1} {nominations 1}]} {score 3.317898988723755}] [{_id ObjectID("573a13bbf29313caabd52ff4")} {title How to Train Your Dragon} {awards [{wins 32} {nominations 51} {text Nominated for 2 Oscars. Another 30 wins & 51 nominations.}]} {score 2.228306293487549}] [{_id ObjectId("64de50da2932de4dd3204393")} {title how to train your dragon} {awards [{wins 32} {nominations 51}]} {score 2.228306293487549}] [{_id ObjectID("573a13ccf29313caabd83281")} {title How to Train Your Dragon 2} {awards [{wins 18} {nominations 52} {text Nominated for 1 Oscar. Another 17 wins & 52 nominations.}]} {score 2.008449077606201}]
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
[{_id ObjectID("573a139cf29313caabcf662c")} {title Atomic Train} {awards [{wins 1} {nominations 1} {text 1 win & 1 nomination.}]} {score 3.3326687812805176}] [{_id ObjectID("573a13bbf29313caabd52ff4")} {title How to Train Your Dragon} {awards [{wins 32} {nominations 51} {text Nominated for 2 Oscars. Another 30 wins & 51 nominations.}]} {score 2.2382168769836426}] [{_id ObjectID("573a13ccf29313caabd83281")} {title How to Train Your Dragon 2} {awards [{wins 18} {nominations 52} {text Nominated for 1 Oscar. Another 17 wins & 52 nominations.}]} {score 2.0173802375793457}] [{_id ObjectID("573a13b1f29313caabd36490")} {title Howard Zinn: You Can't Be Neutral on a Moving Train} {awards [{wins 1} {nominations 0} {text 1 win.}]} {score 1.446497917175293}] [{_id ObjectID("573a13c8f29313caabd78a6b")} {title Last Train Home} {awards [{wins 14} {nominations 9} {text 14 wins & 9 nominations.}]} {score 2.8655927181243896}]
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
쿼리를 복사하여 CaseInsensitiveQuery.java
파일에 붙여넣습니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Aggregates.limit; 3 import static com.mongodb.client.model.Aggregates.project; 4 import static com.mongodb.client.model.Projections.*; 5 import com.mongodb.client.MongoClient; 6 import com.mongodb.client.MongoClients; 7 import com.mongodb.client.MongoCollection; 8 import com.mongodb.client.MongoDatabase; 9 import org.bson.Document; 10 11 public class CaseInsensitiveQuery { 12 public static void main( String[] args ) { 13 // define query 14 Document agg = 15 new Document("$search", 16 new Document("index", "case-insensitive-sort") 17 .append("text", 18 new Document("path", "title") 19 .append("query", "train")) 20 .append("sort", 21 new Document("title", 1))); 22 23 // specify connection 24 String uri = "<connection-string>"; 25 26 // establish connection and set namespace 27 try (MongoClient mongoClient = MongoClients.create(uri)) { 28 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 29 MongoCollection<Document> collection = database.getCollection("movies"); 30 31 // run query and print results 32 collection.aggregate(Arrays.asList(agg, 33 limit(5), 34 project(fields(include("_id"), include("title"), include("awards"), computed("score", new Document("$meta", "searchScore")))))) 35 .forEach(doc -> System.out.println(doc.toJson())); 36 } 37 } 38 }
쿼리에서 <connection-string>
을 바꾼 다음 파일을 저장합니다.
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.
CaseInsensitiveQuery.java
파일을 컴파일하고 실행합니다.
javac CaseInsensitiveQuery.java java CaseInsensitiveQuery
{"_id": {"$oid": "573a139cf29313caabcf662c"}, "title": "Atomic Train", "awards": {"wins": 1, "nominations": 1, "text": "1 win & 1 nomination."}, "score": 3.317898988723755} {"_id": {"$oid": "64de50ae2932de4dd3203061"}, "title": "atomic train", "awards": {"wins": 1, "nominations": 1}, "score": 3.317898988723755} {"_id": {"$oid": "573a13bbf29313caabd52ff4"}, "title": "How to Train Your Dragon", "awards": {"wins": 32, "nominations": 51, "text": "Nominated for 2 Oscars. Another 30 wins & 51 nominations."}, "score": 2.228306293487549} {"_id": {"$oid": "64de50da2932de4dd3204393"}, "title": "how to train your dragon", "awards": {"wins": 32, "nominations": 51}, "score": 2.228306293487549} {"_id": {"$oid": "573a13ccf29313caabd83281"}, "title": "How to Train Your Dragon 2", "awards": {"wins": 18, "nominations": 52, "text": "Nominated for 1 Oscar. Another 17 wins & 52 nominations."}, "score": 2.008449077606201}
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
{"_id": {"$oid": "573a139cf29313caabcf662c"}, "title": "Atomic Train", "awards": {"wins": 1, "nominations": 1, "text": "1 win & 1 nomination."}, "score": 3.3326687812805176} {"_id": {"$oid": "573a13bbf29313caabd52ff4"}, "title": "How to Train Your Dragon", "awards": {"wins": 32, "nominations": 51, "text": "Nominated for 2 Oscars. Another 30 wins & 51 nominations."}, "score": 2.2382168769836426} {"_id": {"$oid": "573a13ccf29313caabd83281"}, "title": "How to Train Your Dragon 2", "awards": {"wins": 18, "nominations": 52, "text": "Nominated for 1 Oscar. Another 17 wins & 52 nominations."}, "score": 2.0173802375793457} {"_id": {"$oid": "573a13b1f29313caabd36490"}, "title": "Howard Zinn: You Can't Be Neutral on a Moving Train", "awards": {"wins": 1, "nominations": 0, "text": "1 win."}, "score": 1.446497917175293} {"_id": {"$oid": "573a13c8f29313caabd78a6b"}, "title": "Last Train Home", "awards": {"wins": 14, "nominations": 9, "text": "14 wins & 9 nominations."}, "score": 2.8655927181243896}
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
다음 코드를 복사하여 CaseInsensitiveQuery.kt
파일에 붙여넣습니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 15 runBlocking { 16 // define query 17 val agg = Document( 18 "\$search", 19 Document("index", "case-insensitive-sort") 20 .append( 21 "text", 22 Document("path", "title") 23 .append("query", "train") 24 ) 25 .append( 26 "sort", 27 Document("title", 1) 28 ) 29 ) 30 31 // run query and print results 32 val resultsFlow = collection.aggregate<Document>( 33 listOf( 34 agg, 35 limit(5), 36 project(fields( 37 excludeId(), 38 include("title", "awards"), 39 computed("score", Document("\$meta", "searchScore")) 40 )) 41 ) 42 ) 43 resultsFlow.collect { println(it) } 44 } 45 mongoClient.close() 46 }
쿼리에서 <connection-string>
을 바꾼 다음 파일을 저장합니다.
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.
CaseInsensitiveQuery.kt
파일을 실행합니다.
IDE에서 CaseInsensitiveQuery.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.
Document{{title=atomic train, awards=Document{{wins=1, nominations=1}}, score=3.3326687812805176}} Document{{title=Atomic Train, awards=Document{{wins=1, nominations=1, text=1 win & 1 nomination.}}, score=3.3326687812805176}} Document{{title=how to train your dragon, awards=Document{{wins=32, nominations=51}}, score=2.2382168769836426}} Document{{title=How to Train Your Dragon, awards=Document{{wins=32, nominations=51, text=Nominated for 2 Oscars. Another 30 wins & 51 nominations.}}, score=2.2382168769836426}} Document{{title=How to Train Your Dragon 2, awards=Document{{wins=18, nominations=52, text=Nominated for 1 Oscar. Another 17 wins & 52 nominations.}}, score=2.0173802375793457}}
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
Document{{title=Atomic Train, awards=Document{{wins=1, nominations=1, text=1 win & 1 nomination.}}, score=3.3326687812805176}} Document{{title=How to Train Your Dragon, awards=Document{{wins=32, nominations=51, text=Nominated for 2 Oscars. Another 30 wins & 51 nominations.}}, score=2.2382168769836426}} Document{{title=How to Train Your Dragon 2, awards=Document{{wins=18, nominations=52, text=Nominated for 1 Oscar. Another 17 wins & 52 nominations.}}, score=2.0173802375793457}} Document{{title=Howard Zinn: You Can't Be Neutral on a Moving Train, awards=Document{{wins=1, nominations=0, text=1 win.}}, score=1.446497917175293}} Document{{title=Last Train Home, awards=Document{{wins=14, nominations=9, text=14 wins & 9 nominations.}}, score=2.8655927181243896}}
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
샘플 쿼리를 복사하여 case-insensitive-query.js
파일에 붙여넣습니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployments connection string. 4 const uri = 5 "<connection-string>"; 6 7 const client = new MongoClient(uri); 8 9 async 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 = [ 19 { 20 '$search': { 21 'index': 'case-insensitive-sort', 22 'text': { 'path': 'title', 'query': 'train' }, 23 'sort': { 'title': 1 } 24 } 25 }, { 26 '$limit': 5 27 }, { 28 '$project': { '_id': 1, 'title': 1, 'awards': 1, 'score': { '$meta': 'searchScore' }} 29 } 30 ]; 31 32 // run pipeline 33 const result = await coll.aggregate(agg); 34 35 // print results 36 await result.forEach((doc) => console.log(doc)); 37 38 } finally { 39 await client.close(); 40 } 41 } 42 run().catch(console.dir);
쿼리에서 <connection-string>
을 바꾼 다음 파일을 저장합니다.
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.
컬렉션을 쿼리합니다.
다음 명령을 실행하여 컬렉션을 쿼리합니다.
node case-insensitive-query.js
{ _id: new ObjectId("573a139cf29313caabcf662c"), title: 'Atomic Train', awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' }, score: 3.317898988723755 } { _id: new ObjectId("64de50ae2932de4dd3203061"), title: 'atomic train', awards: { wins: 1, nominations: 1 }, score: 3.317898988723755 } { _id: new ObjectId("573a13bbf29313caabd52ff4"), title: 'How to Train Your Dragon', awards: { wins: 32, nominations: 51, text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.' }, score: 2.228306293487549 } { _id: new ObjectId("64de50da2932de4dd3204393"), title: 'how to train your dragon', awards: { wins: 32, nominations: 51 }, score: 2.228306293487549 } { _id: new ObjectId("573a13ccf29313caabd83281"), title: 'How to Train Your Dragon 2', awards: { wins: 18, nominations: 52, text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.' }, score: 2.008449077606201 }
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
{ _id: new ObjectId("573a139cf29313caabcf662c"), title: 'Atomic Train', awards: { wins: 1, nominations: 1, text: '1 win & 1 nomination.' }, score: 3.3326687812805176 } { _id: new ObjectId("573a13bbf29313caabd52ff4"), title: 'How to Train Your Dragon', awards: { wins: 32, nominations: 51, text: 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.' }, score: 2.2382168769836426 } { _id: new ObjectId("573a13ccf29313caabd83281"), title: 'How to Train Your Dragon 2', awards: { wins: 18, nominations: 52, text: 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.' }, score: 2.0173802375793457 } { _id: new ObjectId("573a13b1f29313caabd36490"), title: "Howard Zinn: You Can't Be Neutral on a Moving Train", awards: { wins: 1, nominations: 0, text: '1 win.' }, score: 1.446497917175293 } { _id: new ObjectId("573a13c8f29313caabd78a6b"), title: 'Last Train Home', awards: { wins: 14, nominations: 9, text: '14 wins & 9 nominations.' }, score: 2.8655927181243896 }
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.
쿼리를 복사하여 case-insensitive-query.py
파일에 붙여넣습니다.
다음 쿼리는 대소문자에 관계없이 결과를 정렬하는 방법을 보여줍니다. 텍스트 연산자를 사용하여 title
필드에 train
이라는 용어가 있는 영화를 검색한 다음 결과를 title
필드 값을 기준으로 오름차순으로 정렬합니다.
쿼리는 결과의 문서를 5
(으)로 제한하는 $limit
단계와 다음을 수행하는 $project
단계를 지정합니다.
결과에
_id
,title
및awards
필드만 포함합니다.결과에 score라는 필드를 추가합니다.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$search': { 10 'index': 'case-insensitive-sort', 11 'text': { 'path': 'title', 'query': 'train' }, 12 'sort': { 'title': 1 } 13 } 14 }, { 15 '$limit': 5 16 }, { 17 '$project': { '_id': 1, 'title': 1, 'awards': 1, 'score': { '$meta': 'searchScore' } } 18 } 19 ] 20 21 # run pipeline 22 result = client['sample_mflix']['movies'].aggregate(pipeline) 23 24 # print results 25 for i in result: 26 print(i)
쿼리에서 <connection-string>
을 바꾼 다음 파일을 저장합니다.
연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.
명령을 실행하여 컬렉션을 쿼리합니다.
python case-insensitive-query.py
{'_id': ObjectId('573a139cf29313caabcf662c'), 'title': 'Atomic Train', 'awards': {'wins': 1, 'nominations': 1, 'text': '1 win & 1 nomination.'}, 'score': 3.317898988723755} {'_id': ObjectId('64de50ae2932de4dd3203061'), 'title': 'atomic train', 'awards': {'wins': 1, 'nominations': 1}, 'score': 3.317898988723755} {'_id': ObjectId('573a13bbf29313caabd52ff4'), 'title': 'How to Train Your Dragon', 'awards': {'wins': 32, 'nominations': 51, 'text': 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'}, 'score': 2.228306293487549} {'_id': ObjectId('64de50da2932de4dd3204393'), 'title': 'how to train your dragon', 'awards': {'wins': 32, 'nominations': 51}, 'score': 2.228306293487549} {'_id': ObjectId('573a13ccf29313caabd83281'), 'title': 'How to Train Your Dragon 2', 'awards': {'wins': 18, 'nominations': 52, 'text': 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'}, 'score': 2.008449077606201}
결과에는 대소문자에 관계없이 정렬된 문서가 포함됩니다. 그러나 normalizer
을 none
로 설정하면 Atlas Search는 다음과 같은 결과를 반환합니다.
{'_id': ObjectId('573a139cf29313caabcf662c'), 'title': 'Atomic Train', 'awards': {'wins': 1, 'nominations': 1, 'text': '1 win & 1 nomination.'}, 'score': 3.3326687812805176} {'_id': ObjectId('573a13bbf29313caabd52ff4'), 'title': 'How to Train Your Dragon', 'awards': {'wins': 32, 'nominations': 51, 'text': 'Nominated for 2 Oscars. Another 30 wins & 51 nominations.'}, 'score': 2.2382168769836426} {'_id': ObjectId('573a13ccf29313caabd83281'), 'title': 'How to Train Your Dragon 2', 'awards': {'wins': 18, 'nominations': 52, 'text': 'Nominated for 1 Oscar. Another 17 wins & 52 nominations.'}, 'score': 2.0173802375793457} {'_id': ObjectId('573a13b1f29313caabd36490'), 'title': "Howard Zinn: You Can't Be Neutral on a Moving Train", 'awards': {'wins': 1, 'nominations': 0, 'text': '1 win.'}, 'score': 1.446497917175293} {'_id': ObjectId('573a13c8f29313caabd78a6b'), 'title': 'Last Train Home', 'awards': {'wins': 14, 'nominations': 9, 'text': '14 wins & 9 nominations.'}, 'score': 2.8655927181243896}
대소문자를 정규화하지 않고 결과를 정렬하려면 인덱스 정의에서 normalizer
옵션을 none
(7 행)으로 설정하고, 인덱스 정의를 저장한 후 쿼리를 다시 실행합니다.