날짜 범위 필터를 사용한 Atlas Search 쿼리 실행 방법
이 페이지의 내용
이 자습서에서는 동적 매핑을 사용하여 sample_mflix.movies
컬렉션에 인덱스를 생성하는 방법을 설명합니다. released
필드에 대해 복합 쿼리를 실행하고 범위 및 근사 연산자를 사용하는 방법을 보여줍니다. 다음 단계에 따르세요.
sample_mflix.movies
collection에 대한 동적 매핑을 사용하여 Atlas Search 인덱스를 설정합니다.sample_mflix.movies
컬렉션의released
필드에 대해 Atlas Search 복합 쿼리를 실행합니다.
시작하기 전에 Atlas 클러스터가 필수구성 요소에 설명된 요건을 충족하는지 확인하십시오.
Atlas Search 인덱스를 생성하려면 프로젝트에 대한 Project Data Access Admin
이상의 액세스 권한이 있어야 합니다.
동적 매핑으로 Atlas Search 인덱스 만들기
이 섹션에서는 동적 매핑을 사용하여 sample_mflix.movies
컬렉션의 필드를 인덱싱하는 Atlas Search 인덱스를 생성합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
클러스터 페이지가 표시됩니다.
Index Name을 입력하고 Database and Collection을 설정합니다.
Index Name 필드에
date-range-tutorial
를 입력합니다.인덱스 이름을
default
로 지정하면 $search 파이프라인 단계에서index
매개변수를 지정할 필요가 없습니다. 인덱스에 사용자 지정 이름을 지정하는 경우index
매개변수에 이 이름을 지정해야 합니다.Database and Collection 섹션에서
sample_mflix
데이터베이스를 찾고movies
컬렉션을 선택합니다.
인덱스 정의를 지정합니다.
동적 매핑 또는 정적 매핑을 사용하는 Atlas Search 인덱스를 만들 수 있습니다. 동적 및 정적 매핑에 대해 자세히 알아보려면 정적 및 동적 매핑을 참조하세요.
다음 인덱스 정의는 movies
컬렉션에서 지원되는 유형의 필드를 동적으로 인덱싱합니다. Atlas user 인터페이스에서 Atlas Search Visual Editor 또는 Atlas Search JSON Editor을(를) 사용하여 인덱스를 생성할 수 있습니다.
비주얼 편집기
Next를 클릭합니다.
movies
컬렉션에 대한"date-range-tutorial"
인덱스 정의를 검토합니다.
JSON 에디터
Next를 클릭합니다.
인덱스 정의를 검토합니다.
인덱스 정의는 다음과 비슷해야 합니다:
{ "mappings": { "dynamic": true } } 위의 인덱스 정의는
movies
컬렉션의 각 문서에서 지원되는 유형의 필드를 동적으로 인덱싱합니다.Next를 클릭합니다.
복합 쿼리 실행
Select your language 드롭다운 메뉴를 사용하여 이 페이지에서 예시의 언어를 설정합니다.
복합 연산자를 사용하여 두 개 이상의 연산자와 절을 단일 쿼리로 결합할 수 있습니다. 이 튜토리얼에서는 복합 연산자 절을 사용하여 지정된 날짜 범위의 영화를 검색합니다. 이 섹션에서는 Atlas 클러스터에 연결하고 sample_mflix.movies
collection의 released
필드에 대해 복합 연산자를 사용하여 샘플 쿼리를 실행합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
다음 예에서는 하위 쿼리와 함께 compound
연산자를 사용하여 2010
부터 2015
까지의 영화를 검색합니다. 이 쿼리는 다음 절을 사용합니다:
2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는 $limit
단계와 다음을 위한 $project
단계가 포함됩니다.
title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
1 [ 2 { 3 $search: { 4 "index": "date-range-tutorial", 5 "compound": { 6 "must": [{ 7 "range": { 8 "path": "released", 9 "gt": ISODate("2015-01-01T00:00:00.000Z"), 10 "lt": ISODate("2015-12-31T00:00:00.000Z") 11 } 12 }], 13 "should": [{ 14 "near": { 15 "path": "released", 16 "origin": ISODate("2015-07-01T00:00:00.000+00:00"), 17 "pivot": 2629800000 18 } 19 }] 20 } 21 } 22 } 23 ]
SCORE: 2 _id: "573a13c4f29313caabd6c383" fullplot: "When John Connor (Jason Clarke), leader of the human resistance, sends…" imdb: Object year: 2015 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13d9f29313caabdaa9e2" fullplot: "Three years after Mike bowed out of the stripper life at the top of hi…" imdb: Object year: 2015 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13e9f29313caabdcd223" plot: "A documentary about the power of transformation told through the eyes …" genres: Array runtime: 87 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13f4f29313caabde1138" plot: "Dedicated home care nurse Vlasta lives for her husband Lada, her daugh…" genres: Array runtime: 92 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13f9f29313caabdeb320" plot: "For anyone who has not fully understood the controversial Bitcoin yet,…" genres: Array runtime: 60 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13c2f29313caabd67986" plot: "A man wakes up alone in the middle of the desert with a black hood on …" genres: Array runtime: 90 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13f4f29313caabde14cf" plot: "In 1836 the Danish romantic visionary Wulff travels to Africa to creat…" genres: Array runtime: 114 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13d6f29313caabd9f77d" plot: "The plot of the film has a grandfather telling his grand kids the stor…" genres: Array runtime: 78 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e3f29313caabdbfb00" plot: "The story of Amy Winehouse in her own words, featuring unseen archival…" genres: Array runtime: 128 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdcbe1e" plot: "A modern day train hopper fighting to become a successful musician, an…" genres: Array runtime: 90 ... released: 2015-07-02T00:00:00.000+00:00 ...
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
다음 예시는 이전 예시에 추가되는 내용입니다.
이 쿼리에는 must
및 should
절 외에도 documentary
장르의 영화가 결과에 포함되지 않도록 지정하는 mustNot
절이 포함되어 있습니다.
1 [ 2 { 3 $search: { 4 "index": "date-range-tutorial", 5 "compound": { 6 "must": [{ 7 "range": { 8 "path": "released", 9 "gt": ISODate("2015-01-01T00:00:00.000Z"), 10 "lt": ISODate("2015-12-31T00:00:00.000Z") 11 } 12 }], 13 "should": [{ 14 "near": { 15 "path": "released", 16 "origin": ISODate("2015-07-01T00:00:00.000+00:00"), 17 "pivot": 2629800000 18 } 19 }], 20 "mustNot": [{ 21 "text": { 22 "query": "documentary", 23 "path": "genres" 24 } 25 }] 26 } 27 } 28 } 29 ]
SCORE: 2 _id: "573a13c4f29313caabd6c383" fullplot: "When John Connor (Jason Clarke), leader of the human resistance, sends…" imdb: Object year: 2015 ... genres: 0: "Action" 1: "Adventure" 2: "Sci-Fi" ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13d9f29313caabdaa9e2" fullplot: "Three years after Mike bowed out of the stripper life at the top of hi…" imdb: Object year: 2015 ... genres: 0: "Comedy" 1: "Drama" 2: "Music" ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 2 _id: "573a13f4f29313caabde1138" plot: "Dedicated home care nurse Vlasta lives for her husband Lada, her daugh…" genres: 0: "Comedy" 1: "Drama" runtime: 92 ... released: 2015-07-01T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13c2f29313caabd67986" plot: "A man wakes up alone in the middle of the desert with a black hood on …" genres: 0: "Drama" 1: "Mystery" 2: "Sci-Fi" runtime: 90 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9681909084320068 _id: "573a13f4f29313caabde14cf" plot: "In 1836 the Danish romantic visionary Wulff travels to Africa to creat…" genres: 0: "Drama" 1: "History" 2: "Romance" runtime: 114 ... released: 2015-07-02T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13d6f29313caabd9f77d" plot: "The plot of the film has a grandfather telling his grand kids the stor…" genres: 0: "Animation" 1: "Family" runtime: 78 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdcbe1e" plot: "A modern day train hopper fighting to become a successful musician, an…" genres: 0: "Drama" runtime: 90 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9383430480957031 _id: "573a13e9f29313caabdccb5b" plot: "A fancy garden party turns into upper class prey when a colony of kill…" genres: 0: "Comedy" 1: "Horror" runtime: 87 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.9102803468704224 _id: "573a13faf29313caabdec74f" countries: Array genres: 0: "Drama" runtime: 104 ... released: 2015-07-03T00:00:00.000+00:00 ... SCORE: 1.8838474750518799 _id: "573a13eef29313caabdd531d" plot: "A fantasy love story that drifts between this world and heaven. Chasuk…" genres: 0: "Comdedy" countries: Array ... released: 2015-06-27T00:00:00.000+00:00 ...
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
mongosh
에서 클러스터에 연결합니다.
터미널 창에서 mongosh
를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh
를 통한 연결을 참조하세요.
sample_mflix
데이터베이스를 사용합니다.
mongosh
프롬프트에서 다음 명령을 실행합니다.
use sample_mflix
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
다음 예에서는 하위 쿼리와 함께 compound
연산자를 사용하여 2010
부터 2015
까지의 영화를 검색합니다. 이 쿼리는 다음 절을 사용합니다:
2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는 $limit
단계와 다음을 위한 $project
단계가 포함됩니다.
title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
db.movies.aggregate([ { "$search": { "index": "date-range-tutorial", "compound": { "must": [{ "range": { "path": "released", "gt": ISODate("2015-01-01T00:00:00.000Z"), "lt": ISODate("2015-12-31T00:00:00.000Z") } }], "should": [{ "near": { "path": "released", "origin": ISODate("2015-07-01T00:00:00.000+00:00"), "pivot": 2629800000 } }] } } }, { "$limit": 6 }, { "$project": { "_id": 0, "title": 1, "released": 1, "genres": 1, "score": { "$meta": "searchScore" } } } ])
[ { "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "Biography", "Drama" ], "title": "Mala Mala", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "News" ], "title": "Bitcoin: The End of Money as We Know It", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 } ]
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
다음 예시는 이전 예시에 추가되는 내용입니다.
이 쿼리에는 must
및 should
절 외에도 documentary
장르의 영화가 결과에 포함되지 않도록 지정하는 mustNot
절이 포함되어 있습니다.
db.movies.aggregate([ { "$search": { "compound": { "must": [{ "range": { "path": "released", "gt": ISODate("2015-01-01T00:00:00.000Z"), "lt": ISODate("2015-12-31T00:00:00.000Z") } }], "should": [{ "near": { "path": "released", "origin": ISODate("2015-07-01T00:00:00.000+00:00"), "pivot": 2629800000 } }], "mustNot": [{ "text": { "query": "documentary", "path": "genres" } }] } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "released": 1, "genres": 1, "score": { "$meta": "searchScore" } } } ])
[ { "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Drama", "History", "Romance" ], "title": "Gold Coast", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Animation", "Family" ], "title": "Zarafa", "released": ISODate("2015-07-03T00:00:00.000Z"), "score": 1.9383430480957031 } ]
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
다음 예에서는 하위 쿼리와 함께 compound
연산자를 사용하여 2010
부터 2015
까지의 영화를 검색합니다. 이 쿼리는 다음 절을 사용합니다:
2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는 $limit
단계와 다음을 위한 $project
단계가 포함됩니다.
title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
파이프라인 단계 | 쿼리 | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||||||||||||
|
| |||||||||||||||||||
|
|
Auto Preview를 활성화한 경우 MongoDB Compass는 $project
파이프라인 단계 옆에 다음 문서를 표시합니다.
{ "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "Biography", "Drama" ], "title": "Mala Mala", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Documentary", "News" ], "title": "Bitcoin: The End of Money as We Know It", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
다음 예시는 이전 예시에 추가되는 내용입니다.
이 쿼리에는 must
및 should
절 외에도 documentary
장르의 영화가 결과에 포함되지 않도록 지정하는 mustNot
절이 포함되어 있습니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
파이프라인 단계 | 쿼리 | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||||||||||||||||||
|
| |||||||||||||||||||||||||
|
|
Auto Preview를 활성화한 경우 MongoDB Compass는 $project
파이프라인 단계 옆에 다음 문서를 표시합니다.
{ "genres": [ "Action", "Adventure", "Sci-Fi" ], "title": "Terminator Genisys", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama", "Music" ], "title": "Magic Mike XXL", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Comedy", "Drama" ], "title": "Home Care", "released": ISODate("2015-07-01T00:00:00.000Z"), "score": 2 }, { "genres": [ "Drama", "Mystery", "Sci-Fi" ], "title": "Pig", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Drama", "History", "Romance" ], "title": "Gold Coast", "released": ISODate("2015-07-02T00:00:00.000Z"), "score": 1.9681909084320068 }, { "genres": [ "Animation", "Family" ], "title": "Zarafa", "released": ISODate("2015-07-03T00:00:00.000Z"), "score": 1.9383430480957031 }
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
Program.cs
파일에서 두 개의 절을 가진 compound
연산자를 사용하여 Atlas Search 쿼리를 생성하고 실행합니다.
Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음
compound
연산자 절을 사용하여 collection을 쿼리합니다.2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는
$limit
단계와 다음을 위한$project
단계가 포함됩니다.title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
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 DateRangeExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // declare data for compound query 23 var startDate = new DateTime(2015, 01, 01, 0, 0, 0, DateTimeKind.Utc); 24 var endDate = new DateTime(2015, 12, 31, 0, 0, 0, DateTimeKind.Utc); 25 var nearDate = new DateTime(2015, 07, 01, 0, 0, 0, DateTimeKind.Utc); 26 27 // define and run pipeline 28 var results = moviesCollection.Aggregate() 29 .Search(Builders<MovieDocument>.Search.Compound() 30 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate))) 31 .Should(Builders<MovieDocument>.Search.Near(movie => movie.Released, nearDate, 2629800000)), 32 indexName: "date-range-tutorial") 33 .Project<MovieDocument>(Builders<MovieDocument>.Projection 34 .Include(movie => movie.Genres) 35 .Include(movie => movie.Released) 36 .Include(movie => movie.Title) 37 .Exclude(movie => movie.Id) 38 .MetaSearchScore(movie => movie.Score)) 39 .Limit(6) 40 .ToList(); 41 42 // print results 43 foreach (var movie in results) 44 { 45 Console.WriteLine(movie.ToJson()); 46 } 47 } 48 } 49 50 [ ]51 public class MovieDocument 52 { 53 [ ]54 public ObjectId Id { get; set; } 55 public string [] Genres { get; set; } 56 public DateTime Released { get; set; } 57 public string Title { get; set; } 58 public double Score { get; set; } 59 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.Program.cs
파일을 컴파일하고 실행합니다.dotnet run date-range-example.csproj { "genres" : ["Action", "Adventure", "Sci-Fi"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Terminator Genisys", "score" : 2.0 } { "genres" : ["Comedy", "Drama", "Music"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Magic Mike XXL", "score" : 2.0 } { "genres" : ["Documentary", "Biography", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Mala Mala", "score" : 2.0 } { "genres" : ["Comedy", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Home Care", "score" : 2.0 } { "genres" : ["Documentary", "News"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Bitcoin: The End of Money as We Know It", "score" : 2.0 } { "genres" : ["Drama", "Mystery", "Sci-Fi"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Pig", "score" : 1.9681909084320068 }
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
Program.cs
파일에서 세 개의 절을 가진 compound
연산자를 사용하여 Atlas Search 쿼리를 생성하고 실행합니다.
Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
이전 예시에 추가합니다.
이 쿼리에는
must
및should
절 외에도documentary
장르의 영화가 결과에 포함되지 않도록 지정하는mustNot
절이 포함되어 있습니다.커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
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 DateRangeComplexExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // declare data for compound query 23 var startDate = new DateTime(2015, 01, 01, 0, 0, 0, DateTimeKind.Utc); 24 var endDate = new DateTime(2015, 12, 31, 0, 0, 0, DateTimeKind.Utc); 25 var nearDate = new DateTime(2015, 07, 01, 0, 0, 0, DateTimeKind.Utc); 26 27 // define and run pipeline 28 var results = moviesCollection.Aggregate() 29 .Search(Builders<MovieDocument>.Search.Compound() 30 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate))) 31 .Should(Builders<MovieDocument>.Search.Near(movie => movie.Released, nearDate, 2629800000)) 32 .MustNot(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Documentary")), 33 indexName: "date-range-tutorial") 34 .Project<MovieDocument>(Builders<MovieDocument>.Projection 35 .Include(movie => movie.Genres) 36 .Include(movie => movie.Released) 37 .Include(movie => movie.Title) 38 .Exclude(movie => movie.Id) 39 .MetaSearchScore(movie => movie.Score)) 40 .Limit(6) 41 .ToList(); 42 43 // print results 44 foreach (var movie in results) 45 { 46 Console.WriteLine(movie.ToJson()); 47 } 48 } 49 } 50 51 [ ]52 public class MovieDocument 53 { 54 [ ]55 public ObjectId Id { get; set; } 56 public string [] Genres { get; set; } 57 public DateTime Released { get; set; } 58 public string Title { get; set; } 59 public double Score { get; set; } 60 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.Program.cs
파일을 컴파일하고 실행합니다.dotnet run date-range-example.csproj { "genres" : ["Action", "Adventure", "Sci-Fi"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Terminator Genisys", "score" : 2.0 } { "genres" : ["Comedy", "Drama", "Music"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Magic Mike XXL", "score" : 2.0 } { "genres" : ["Comedy", "Drama"], "released" : ISODate("2015-07-01T00:00:00Z"), "title" : "Home Care", "score" : 2.0 } { "genres" : ["Drama", "Mystery", "Sci-Fi"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Pig", "score" : 1.9681909084320068 } { "genres" : ["Drama", "History", "Romance"], "released" : ISODate("2015-07-02T00:00:00Z"), "title" : "Gold Coast", "score" : 1.9681909084320068 } { "genres" : ["Animation", "Family"], "released" : ISODate("2015-07-03T00:00:00Z"), "title" : "Zarafa", "score" : 1.9383430480957031 }
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
date-range.go
이라는 파일을 만듭니다.다음 코드를 복사하여
date-range.go
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음
compound
연산자 절을 사용하여 collection을 쿼리합니다.2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는
$limit
단계와 다음을 위한$project
단계가 포함됩니다.title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
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": "date-range-tutorial", 27 "compound": bson.M{ 28 "must": bson.M{ 29 "range": bson.M{ 30 "path": "released", 31 "gt": time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC), 32 "lt": time.Date(2015, time.December, 31, 0, 0, 0, 0, time.UTC), 33 }}, 34 "should": bson.D{ 35 {"near", bson.M{ 36 "path": "released", 37 "origin": time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC), 38 "pivot": 2629800000, 39 }}}, 40 }}}} 41 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 42 limitStage := bson.D{{"$limit", 6}} 43 44 // run pipeline 45 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage}) 46 if err != nil { 47 panic(err) 48 } 49 50 // print results 51 var results []bson.D 52 if err = cursor.All(context.TODO(), &results); err != nil { 53 panic(err) 54 } 55 for _, result := range results { 56 fmt.Println(result) 57 } 58 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.다음 명령을 실행하여 컬렉션을 쿼리합니다.
go run date-range.go [{genres [Action Adventure Sci-Fi]} {title Terminator Genisys} {released 1435708800000} {score 2}] [{genres [Comedy Drama Music]} {title Magic Mike XXL} {released 1435708800000} {score 2}] [{genres [Documentary Biography Drama]} {title Mala Mala} {released 1435708800000} {score 2}] [{genres [Comedy Drama]} {title Home Care} {released 1435708800000} {score 2}] [{genres [Documentary News]} {title Bitcoin: The End of Money as We Know It} {released 1435708800000} {score 2}] [{genres [Drama Mystery Sci-Fi]} {title Pig} {released 1435795200000} {score 1.9681909084320068}] 쿼리의 경우
should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
date-range-complex.go
이라는 파일을 만듭니다.다음 코드를 복사하여
date-range-complex.go
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
이전 예시에 추가합니다.
이 쿼리에는
must
및should
절 외에도documentary
장르의 영화가 결과에 포함되지 않도록 지정하는mustNot
절이 포함되어 있습니다.커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
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": "date-range-tutorial", 27 "compound": bson.M{ 28 "must": bson.M{ 29 "range": bson.M{ 30 "path": "released", 31 "gt": time.Date(2015, time.January, 1, 0, 0, 0, 0, time.UTC), 32 "lt": time.Date(2015, time.December, 31, 0, 0, 0, 0, time.UTC), 33 }}, 34 "should": bson.D{ 35 {"near", bson.M{ 36 "path": "released", 37 "origin": time.Date(2015, time.July, 1, 0, 0, 0, 0, time.UTC), 38 "pivot": 2629800000, 39 }}}, 40 "mustNot": bson.D{ 41 {"text", bson.M{ 42 "path": "genres", "query": "Documentary", 43 }}}, 44 }}}} 45 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 46 limitStage := bson.D{{"$limit", 6}} 47 48 // run pipeline 49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage, limitStage}) 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 date-range-complex.go [{genres [Action Adventure Sci-Fi]} {title Terminator Genisys} {released 1435708800000} {score 2}] [{genres [Comedy Drama Music]} {title Magic Mike XXL} {released 1435708800000} {score 2}] [{genres [Comedy Drama]} {title Home Care} {released 1435708800000} {score 2}] [{genres [Drama Mystery Sci-Fi]} {title Pig} {released 1435795200000} {score 1.9681909084320068}] [{genres [Drama History Romance]} {title Gold Coast} {released 1435795200000} {score 1.9681909084320068}] [{genres [Animation Family]} {title Zarafa} {released 1435881600000} {score 1.9383430480957031}] 쿼리의 경우
should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
DateRange.java
이라는 파일을 만듭니다.다음 코드를 복사하여
DateRange.java
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음
compound
연산자 절을 사용하여 collection을 쿼리합니다.2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는
$limit
단계와 다음을 위한$project
단계가 포함됩니다.title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
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 DateRange { 17 public static void main( String[] args ) { 18 // define clauses 19 List<Document> mustClauses = 20 List.of( new Document( 21 "range", new Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))))); 24 List<Document> shouldClauses = 25 List.of( 26 new Document( 27 "near", 28 new Document("pivot", 2629800000L) 29 .append("path", "released") 30 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))))); 31 // define query 32 Document agg = 33 new Document( "$search", 34 new Document("index", "date-range-tutorial") 35 .append( "compound", 36 new Document().append("must", mustClauses) 37 .append("should", shouldClauses))); 38 // specify connection 39 String uri = "<connection-string>"; 40 41 // establish connection and set namespace 42 try (MongoClient mongoClient = MongoClients.create(uri)) { 43 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 44 MongoCollection<Document> collection = database.getCollection("movies"); 45 46 // run query and print results 47 collection.aggregate(Arrays.asList(agg, 48 project(fields( 49 excludeId(), 50 include("title", "released", "genres"), 51 computed("score", new Document("$meta", "searchScore")))), 52 limit(6))) 53 .forEach(doc -> System.out.println(doc.toJson())); 54 } 55 } 56 } 참고
Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.
package com.mongodb.drivers; 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.DateRange.java
파일을 컴파일하고 실행합니다.javac DateRange.java java DateRange {"genres": ["Action", "Adventure", "Sci-Fi"], "title": "Terminator Genisys", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama", "Music"], "title": "Magic Mike XXL", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Documentary", "Biography", "Drama"], "title": "Mala Mala", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama"], "title": "Home Care", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Documentary", "News"], "title": "Bitcoin: The End of Money as We Know It", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Drama", "Mystery", "Sci-Fi"], "title": "Pig", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068}
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
DateRangeComplex.java
이라는 파일을 만듭니다.다음 코드를 복사하여
DateRangeComplex.java
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
이전 예시에 추가합니다.
이 쿼리에는
must
및should
절 외에도documentary
장르의 영화가 결과에 포함되지 않도록 지정하는mustNot
절이 포함되어 있습니다.커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
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 DateRangeComplex { 17 public static void main( String[] args ) { 18 // define clauses 19 List<Document> mustClauses = 20 List.of( new Document( 21 "range", new Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))))); 24 List<Document> shouldClauses = 25 List.of( 26 new Document( 27 "near", 28 new Document("pivot", 2629800000L) 29 .append("path", "released") 30 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))))); 31 List<Document> mustNotClauses = 32 List.of( 33 new Document( 34 "text", 35 new Document("query", "Documentary") 36 .append("path", "genres"))); 37 // define query 38 Document agg = 39 new Document( "$search", 40 new Document("index", "date-range-tutorial") 41 .append( "compound", 42 new Document().append("must", mustClauses) 43 .append("should", shouldClauses) 44 .append("mustNot", mustNotClauses))); 45 // specify connection 46 String uri = "<connection-string>"; 47 48 // establish connection and set namespace 49 try (MongoClient mongoClient = MongoClients.create(uri)) { 50 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 51 MongoCollection<Document> collection = database.getCollection("movies"); 52 53 // run query and print results 54 collection.aggregate(Arrays.asList(agg, 55 project(fields( 56 excludeId(), 57 include("title", "released", "genres"), 58 computed("score", new Document("$meta", "searchScore")))), 59 limit(6))) 60 .forEach(doc -> System.out.println(doc.toJson())); 61 } 62 } 63 } 참고
Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.
package com.mongodb.drivers; 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.DateRangeComplex.java
파일을 컴파일하고 실행합니다.javac DateRangeComplex.java java DateRangeComplex {"genres": ["Action", "Adventure", "Sci-Fi"], "title": "Terminator Genisys", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama", "Music"], "title": "Magic Mike XXL", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Comedy", "Drama"], "title": "Home Care", "released": {"$date": "2015-07-01T00:00:00Z"}, "score": 2.0} {"genres": ["Drama", "Mystery", "Sci-Fi"], "title": "Pig", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068} {"genres": ["Drama", "History", "Romance"], "title": "Gold Coast", "released": {"$date": "2015-07-02T00:00:00Z"}, "score": 1.9681909084320068} {"genres": ["Animation", "Family"], "title": "Zarafa", "released": {"$date": "2015-07-03T00:00:00Z"}, "score": 1.9383430480957031}
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
DateRange.kt
이라는 파일을 만듭니다.다음 코드를 복사하여
DateRange.kt
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음
compound
연산자 절을 사용하여 collection을 쿼리합니다.2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는
$limit
단계와 다음을 위한$project
단계가 포함됩니다.title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
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 clauses 19 val mustClauses = listOf( 20 Document( 21 "range", Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))) 24 ) 25 ) 26 27 val shouldClauses = listOf( 28 Document( 29 "near", 30 Document("pivot", 2629800000L) 31 .append("path", "released") 32 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))) 33 ) 34 ) 35 36 // define query 37 val agg = Document( 38 "\$search", 39 Document("index", "date-range-tutorial") 40 .append( 41 "compound", 42 Document().append("must", mustClauses) 43 .append("should", shouldClauses) 44 ) 45 ) 46 47 // run query and print results 48 val resultsFlow = collection.aggregate<Document>( 49 listOf( 50 agg, 51 limit(6), 52 project(fields( 53 excludeId(), 54 include("title", "released", "genres"), 55 computed("score", Document("\$meta", "searchScore")) 56 )) 57 ) 58 ) 59 resultsFlow.collect { println(it) } 60 } 61 mongoClient.close() 62 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.DateRange.kt
파일을 실행합니다.IDE에서
DateRange.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{genres=[Action, Adventure, Sci-Fi], title=Terminator Genisys, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama, Music], title=Magic Mike XXL, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Documentary, News], title=Bitcoin: The End of Money as We Know It, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Documentary, Biography, Drama], title=Mala Mala, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama], title=Home Care, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Drama, Mystery, Sci-Fi], title=Pig, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}}
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
DateRangeComplex.kt
이라는 파일을 만듭니다.다음 코드를 복사하여
DateRangeComplex.kt
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
이전 예시에 추가합니다.
이 쿼리에는
must
및should
절 외에도documentary
장르의 영화가 결과에 포함되지 않도록 지정하는mustNot
절이 포함되어 있습니다.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 clauses 19 val mustClauses = listOf( 20 Document( 21 "range", Document("path", "released") 22 .append("gt", Date.from(Instant.parse("2015-01-01T00:00:00.000Z"))) 23 .append("lt", Date.from(Instant.parse("2015-12-31T00:00:00.000Z"))) 24 ) 25 ) 26 27 val shouldClauses = listOf( 28 Document( 29 "near", 30 Document("pivot", 2629800000L) 31 .append("path", "released") 32 .append("origin", Date.from(Instant.parse("2015-07-01T00:00:00.000+00:00"))) 33 ) 34 ) 35 36 val mustNotClauses = listOf( 37 Document( 38 "text", 39 Document("query", "Documentary") 40 .append("path", "genres") 41 ) 42 ) 43 44 // define query 45 val agg = Document( 46 "\$search", 47 Document("index", "date-range-tutorial") 48 .append( 49 "compound", 50 Document().append("must", mustClauses) 51 .append("should", shouldClauses) 52 .append("mustNot", mustNotClauses) 53 ) 54 ) 55 56 // run query and print results 57 val resultsFlow = collection.aggregate<Document>( 58 listOf( 59 agg, 60 limit(6), 61 project(fields( 62 excludeId(), 63 include("title", "released", "genres"), 64 computed("score", Document("\$meta", "searchScore")) 65 )) 66 ) 67 ) 68 resultsFlow.collect { println(it) } 69 } 70 mongoClient.close() 71 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.DateRangeComplex.kt
파일을 실행합니다.IDE에서
DateRangeComplex.kt
프로그램을 실행하면 다음 문서가 인쇄됩니다.Document{{genres=[Action, Adventure, Sci-Fi], title=Terminator Genisys, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama, Music], title=Magic Mike XXL, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Comedy, Drama], title=Home Care, released=Tue Jun 30 20:00:00 EDT 2015, score=2.0}} Document{{genres=[Drama, Mystery, Sci-Fi], title=Pig, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}} Document{{genres=[Drama, History, Romance], title=Gold Coast, released=Wed Jul 01 20:00:00 EDT 2015, score=1.9681909084320068}} Document{{genres=[Drama], title=Jackie & Ryan, released=Thu Jul 02 20:00:00 EDT 2015, score=1.9383430480957031}}
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
date-range.js
이라는 파일을 만듭니다.다음 코드를 복사하여
date-range.js
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
MongoDB의 Node.js 드라이버인
mongodb
를 가져옵니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음
compound
연산자 절을 사용하여 collection을 쿼리합니다.2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는
$limit
단계와 다음을 위한$project
단계가 포함됩니다.title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 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: 'date-range-tutorial', 21 compound: { 22 must: [{ range: { path: "released", gt: new Date("2015-01-01T00:00:00.000Z"), lt: new Date("2015-12-31T00:00:00.000Z") }}], 23 should: [{ near: { path: "released", origin: new Date("2015-07-01T00:00:00.000Z"), pivot: 2629800000 }}]}}}, 24 { $project: {_id: 0, title: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}}, 25 { $limit: 6 } 26 ]; 27 28 // run pipeline 29 const result = await coll.aggregate(agg); 30 31 // print results 32 await result.forEach((doc) => console.log(doc)); 33 } finally { 34 await client.close(); 35 } 36 } 37 run().catch(console.dir); 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.다음 명령을 실행하여 컬렉션을 쿼리합니다.
node date-range.js { genres: [ 'Action', 'Adventure', 'Sci-Fi' ], title: 'Terminator Genisys', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama', 'Music' ], title: 'Magic Mike XXL', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Documentary', 'Biography', 'Drama' ], title: 'Mala Mala', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama' ], title: 'Home Care', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Documentary', 'News' ], title: 'Bitcoin: The End of Money as We Know It', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Drama', 'Mystery', 'Sci-Fi' ], title: 'Pig', released: 2015-07-02T00:00:00.000Z, score: 1.9681909084320068 }
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
date-range-complex.js
이라는 파일을 만듭니다.다음 코드를 복사하여
date-range-complex.js
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
MongoDB의 Node.js 드라이버인
mongodb
를 가져옵니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.이전 예시에 추가합니다.
이 쿼리에는
must
및should
절 외에도documentary
장르의 영화가 결과에 포함되지 않도록 지정하는mustNot
절이 포함되어 있습니다.커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 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: 'date-range-tutorial', 21 compound: { 22 must: [{ range: { path: "released", gt: new Date("2015-01-01T00:00:00.000Z"), lt: new Date("2015-12-31T00:00:00.000Z") }}], 23 should: [{ near: { path: "released", origin: new Date("2015-07-01T00:00:00.000Z"), pivot: 2629800000 }}], 24 mustNot: [{ text: { path: "genres", query: "Documentary"} }]}}}, 25 { $project: {_id: 0, title: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}}, 26 { $limit: 6 } 27 ]; 28 29 // run pipeline 30 const result = await coll.aggregate(agg); 31 32 // print results 33 await result.forEach((doc) => console.log(doc)); 34 } finally { 35 await client.close(); 36 } 37 } 38 run().catch(console.dir); 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.다음 명령을 실행하여 컬렉션을 쿼리합니다.
node date-range-complex.js { genres: [ 'Action', 'Adventure', 'Sci-Fi' ], title: 'Terminator Genisys', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama', 'Music' ], title: 'Magic Mike XXL', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Comedy', 'Drama' ], title: 'Home Care', released: 2015-07-01T00:00:00.000Z, score: 2 } { genres: [ 'Drama', 'Mystery', 'Sci-Fi' ], title: 'Pig', released: 2015-07-02T00:00:00.000Z, score: 1.9681909084320068 } { genres: [ 'Drama', 'History', 'Romance' ], title: 'Gold Coast', released: 2015-07-02T00:00:00.000Z, score: 1.9681909084320068 } { genres: [ 'Animation', 'Family' ], title: 'Zarafa', released: 2015-07-03T00:00:00.000Z, score: 1.9383430480957031 }
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 두 개의 절을 가진 Atlas Search compound
쿼리를 실행합니다.
date-range.py
이라는 파일을 만듭니다.다음 코드를 복사하여
date-range.py
파일에 붙여넣습니다.다음 코드 예제에서는:
pymongo
, MongoDB의 Python 드라이버 및dns
모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여pymongo
를Atlas
에 연결하는 데 필요합니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.다음
compound
연산자 절을 사용하여 collection을 쿼리합니다.2015-01-01
에서2015-12-31
사이에 개봉된 영화를 검색하는must
절피벗 거리가 1개월인
2012-07-01
근처에 개봉된 영화에 대한 기본 설정을 지정하는should
절.
쿼리에는 출력을 6개 결과로 제한하는
$limit
단계와 다음을 위한$project
단계가 포함됩니다.title
,released
및genres
필드를 제외한 모든 필드 제외다음과 같은 이름의 필드를 추가합니다.
score
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import pymongo 2 import datetime 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient("<connection-string>") 6 7 # define pipeline 8 pipeline = [ 9 {"$search": { 10 "index": "date-range-tutorial", 11 "compound": { 12 "must": [{"range": {"path": "released", "gt": datetime.datetime(2015,1,1,0,0,0), "lt": datetime.datetime(2015,12,31,0,0,0)}}], 13 "should": [{"near": {"path": "released", "origin": datetime.datetime(2015, 7, 1, 0, 0, 0, 0), "pivot": 2629800000}}]}}}, 14 {"$limit": 6}, 15 {"$project": {"_id": 0, "title": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}} 16 ] 17 # run pipeline 18 result = client["sample_mflix"]["movies"].aggregate(pipeline) 19 20 # print results 21 for i in result: 22 print(i) 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.다음 명령을 실행하여 컬렉션을 쿼리합니다.
python date-range.py {'genres': ['Action', 'Adventure', 'Sci-Fi'], 'title': 'Terminator Genisys', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama', 'Music'], 'title': 'Magic Mike XXL', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Documentary', 'Biography', 'Drama'], 'title': 'Mala Mala', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama'], 'title': 'Home Care', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Documentary', 'News'], 'title': 'Bitcoin: The End of Money as We Know It', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Drama', 'Mystery', 'Sci-Fi'], 'title': 'Pig', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068}
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.
movies
컬렉션에서 세 개의 절을 사용하여 Atlas Search compound
쿼리를 실행합니다.
date-range-complex.py
이라는 파일을 만듭니다.다음 코드를 복사하여
date-range-complex.py
파일에 붙여넣습니다.다음 코드 예제에서는:
pymongo
, MongoDB의 Python 드라이버 및dns
모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여pymongo
를Atlas
에 연결하는 데 필요합니다.MongoClient
클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.이전 예시에 추가합니다.
이 쿼리에는
must
및should
절 외에도documentary
장르의 영화가 결과에 포함되지 않도록 지정하는mustNot
절이 포함되어 있습니다.커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 import pymongo 2 import datetime 3 4 # connect to your Atlas cluster 5 client = pymongo.MongoClient("<connection-string>") 6 7 # define pipeline 8 pipeline = [ 9 {"$search": { 10 "index": "date-range-tutorial", 11 "compound": { 12 "must": [{"range": {"path": "released", "gt": datetime.datetime(2015,1,1,0,0,0), "lt": datetime.datetime(2015,12,31,0,0,0)}}], 13 "should": [{"near": {"path": "released", "origin": datetime.datetime(2015, 7, 1, 0, 0, 0, 0), "pivot": 2629800000}}], 14 "mustNot": [{"text": {"path": "genres", "query": "Documentary"}}]}}}, 15 {"$limit": 6}, 16 {"$project": {"_id": 0, "title": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}} 17 ] 18 # run pipeline 19 result = client["sample_mflix"]["movies"].aggregate(pipeline) 20 21 # print results 22 for i in result: 23 print(i) 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.다음 명령을 실행하여 컬렉션을 쿼리합니다.
python date-range-complex.py {'genres': ['Action', 'Adventure', 'Sci-Fi'], 'title': 'Terminator Genisys', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama', 'Music'], 'title': 'Magic Mike XXL', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Comedy', 'Drama'], 'title': 'Home Care', 'released': datetime.datetime(2015, 7, 1, 0, 0), 'score': 2.0} {'genres': ['Drama', 'Mystery', 'Sci-Fi'], 'title': 'Pig', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068} {'genres': ['Drama', 'History', 'Romance'], 'title': 'Gold Coast', 'released': datetime.datetime(2015, 7, 2, 0, 0), 'score': 1.9681909084320068} {'genres': ['Animation', 'Family'], 'title': 'Zarafa', 'released': datetime.datetime(2015, 7, 3, 0, 0), 'score': 1.9383430480957031}
쿼리의 경우 should
절이 7월 근처 영화에 대한 선호도를 지정했기 때문에 상위 결과는 7월에 있습니다.