문서 메뉴
문서 홈
/
MongoDB 아틀라스
/ /

다국어 Atlas 검색 쿼리를 실행하는 방법

이 페이지의 내용

  • Atlas Search 인덱스 만들기
  • 컬렉션 검색

이 튜토리얼에서는 언어 분석기 를 사용하는 인덱스를 만들고 sample_mflix.movies 컬렉션에 대해 다국어 검색을 수행하는 방법을 설명합니다. 다음 단계를 안내합니다.

  1. sample_mflix.movies collection에 대한 동적 매핑을 사용하여 Atlas Search 인덱스를 설정합니다. fullplot 필드를 인덱싱하기 위해 lucene.italian 언어 분석기 또는 lucene.italianlucene.english 언어 분석기를 적용할 수 있습니다. Atlas Search는 collection에서 동적으로 인덱싱하는 다른 모든 필드에 대해 기본 lucene.standard 분석기를 사용합니다.

  2. sample_mflix.movies 컬렉션의 fullplot, releasedgenres 필드에 대해 Atlas Search 복합 쿼리를 실행합니다.

시작하기 전에 Atlas cluster가 필수구성 요소에 설명된 요건을 충족하는지 확인하십시오.

Atlas Search 인덱스를 생성하려면 프로젝트에 대한 Project Data Access Admin 이상의 액세스 권한이 있어야 합니다.

이 섹션에서는 sample_mflix.movies collection의 fullplot 필드에 Atlas Search 검색 인덱스를 생성합니다.

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

  2. 이미 표시되어 있지 않은 경우 Projects 탐색 모음의 프로젝트 메뉴에서 원하는 프로젝트를 선택합니다.

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

2

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

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

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

  1. cluster의 Browse Collections 버튼을 클릭합니다.

  2. 데이터베이스를 확장하고 컬렉션을 선택합니다.

  3. 컬렉션의 Search Indexes 탭을 클릭합니다.

  1. 클러스터의 이름을 클릭합니다.

  2. Atlas Search 탭을 클릭합니다.

3
4
  • 안내를 따라 진행하고자 할 때는 Atlas Search Visual Editor를 선택합니다.

  • 원시 인덱스 정의를 편집하고 싶다면, Atlas Search JSON Editor을 선택합니다.

5
  1. Index Name 필드에 multilingual-tutorial를 입력합니다.

    참고

    인덱스 이름을 default으로 지정하면 $search 파이프라인 단계를 사용할 때 index 매개 변수를 지정할 필요가 없습니다. 그렇지 않으면 index 매개 변수를 사용하여 인덱스 이름을 지정해야 합니다.

  2. Database and Collection 섹션에서 sample_mflix 데이터베이스를 찾고 movies 컬렉션을 선택합니다.

6

Atlas user 인터페이스에서 Atlas Search Visual Editor 또는 Atlas Search JSON Editor 을(를) 사용하여 인덱스를 생성할 수 있습니다. 인덱스를 설정하여 fullplot 필드를 이탈리아 언어만 사용하거나 이탈리아와 영어를 모두 사용할 수 있습니다.

  1. Refine Your Index를 클릭합니다.

  2. Field Mappings 섹션에서 Add Field을 클릭하여 Add Field Mapping 창을 표시합니다.

  3. Field Name 에 대해 fullplot을 선택합니다.

  4. 데이터 유형 설정에서 이탈리아어만 사용하여 필드를 분석할지, 또는 이탈리아와 영어를 모두 사용하여 필드를 분석할지 여부를 구성할 수 있습니다.

    1. Data Type 드롭다운을 클릭하여 String를 선택합니다.

    2. lucene.italian 분석기를 사용하도록 Index AnalyzerSearch Analyzer 을(를) 수정합니다.

      1. Index Analyzer 드롭다운에서 lucene.language 을 선택한 다음 lucene.italian 를 선택합니다.

      2. Search Analyzer 이(가) 자동으로 업데이트되지 않은 경우 Search Analyzer 드롭다운에서 lucene.language 을(를) 선택한 다음 lucene.italian 을(를) 선택합니다.

    1. Data Type 드롭다운을 클릭하여 String를 선택합니다.

    2. lucene.italian 분석기를 사용하도록 Index AnalyzerSearch Analyzer 을(를) 수정합니다.

      1. Index Analyzer 드롭다운에서 lucene.language 을 선택한 다음 lucene.italian 를 선택합니다.

      2. Search Analyzer 이(가) 자동으로 업데이트되지 않은 경우 Search Analyzer 드롭다운에서 lucene.language 을(를) 선택한 다음 lucene.italian 을(를) 선택합니다.

    3. fullplot 필드에 다른 데이터 유형을 정의하려면 Add Multi Field 을 클릭합니다.

    4. Multi Field Name 필드에 fullplot_english 을 입력합니다.

    5. lucene.english 분석기를 사용하도록 Index AnalyzerSearch Analyzer 을(를) 수정합니다.

      1. Index Analyzer 드롭다운에서 lucene.language 을 선택한 다음 lucene.english 를 선택합니다.

      2. Search Analyzer 이(가) 자동으로 업데이트되지 않은 경우 Search Analyzer 드롭다운에서 lucene.language 을(를) 선택한 다음 lucene.english 을(를) 선택합니다.

  5. Add를 클릭합니다.

  6. Index Configurations 섹션에서 다음 설정을 확인하고 필요한 경우 변경합니다.

    • Index AnalyzerSearch Analyzerlucene.standard 사용

    • 활성화 Dynamic Mapping

  7. Save Changes를 클릭합니다.

  1. 기본 정의를 다음으로 바꿉니다.

    {
    "analyzer": "lucene.standard",
    "searchAnalyzer": "lucene.standard",
    "mappings": {
    "dynamic": true,
    "fields": {
    "fullplot": [
    {
    "analyzer": "lucene.italian",
    "searchAnalyzer": "lucene.italian",
    "type": "string"
    }
    ]
    }
    }
    }
    {
    "analyzer": "lucene.standard",
    "searchAnalyzer": "lucene.standard",
    "mappings": {
    "dynamic": true,
    "fields": {
    "fullplot": {
    "type": "string",
    "analyzer": "lucene.italian",
    "searchAnalyzer": "lucene.italian",
    "multi": {
    "fullplot_english": {
    "type": "string",
    "analyzer": "lucene.english",
    "searchAnalyzer": "lucene.english"
    }
    }
    }
    }
    }
    }
  2. Next를 클릭합니다.

7
8

인덱스가 작성 중임을 보여주는 모달 창이 표시됩니다. Close 버튼을 클릭합니다.

9

인덱스 작성에는 약 1분 정도가 소요됩니다. 작성하는 동안 Status 열은 Build in Progress을 읽습니다. 작성이 완료되면 Status 열에 Active이 표시됩니다.


언어 선택 드롭다운 메뉴를 사용하여 이 섹션에 있는 예제의 언어를 설정합니다.


복합 연산자 를 사용하여 두 개 이상의 연산자를 단일 쿼리로 결합할 수 있습니다. 이 섹션에서는 Atlas cluster에 연결하고 compound 연산자를 사용하여 sample_mflix.movies collection에 대해 샘플 쿼리를 실행합니다.

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

  2. 이미 표시되어 있지 않은 경우 Projects 탐색 모음의 프로젝트 메뉴에서 원하는 프로젝트를 선택합니다.

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

2

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

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

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

  1. cluster의 Browse Collections 버튼을 클릭합니다.

  2. 데이터베이스를 확장하고 컬렉션을 선택합니다.

  3. 컬렉션의 Search Indexes 탭을 클릭합니다.

  1. 클러스터의 이름을 클릭합니다.

  2. Atlas Search 탭을 클릭합니다.

3

쿼리할 인덱스 오른쪽에 있는 Query 버튼을 클릭합니다.

4

Edit Query 을 클릭하면 JSON 형식의 기본 쿼리 구문 샘플을 볼 수 있습니다.

5

이 쿼리는 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

  • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

  • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

  • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.

[
{
$search: {
"index": "multilingual-tutorial",
"compound": {
"must": [{
"text": {
"path": "fullplot",
"query": "coppia"
}
}],
"mustNot": [{
"range": {
"path": "released",
"gt": ISODate("2000-01-01T00:00:00.000Z"),
"lt": ISODate("2009-01-01T00:00:00.000Z")
}
}],
"should": [{
"text": {
"query": "Drama",
"path": "genres"
}
}]
}
}
}
]
SCORE: 4.606284141540527 _id: "573a1394f29313caabce0561"
plot: "In a Japanese slum, various residents play out their lives, dreaming o…"
genres:
0: "Drama"
runtime: 137
fullplot: "Una coppia di gretti usurai gestisce uno squallido dormitorio, nei pre…"
released: 1957-10-01T00:00:00.000+00:00
SCORE: 3.9604406356811523 _id: "573a1395f29313caabce26d2"
plot: "Sei persone viaggiano in un vagone-letto da Marsiglia a Parigi. All'ar…"
genres:
0: "Mystery"
1: "Thriller"
runtime: 95
fullplot: "Sei persone viaggiano in un vagone-letto da Marsiglia a Parigi. All'ar…"
released: 1965-11-17T00:00:00.000+00:00
6

Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.

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

  2. 이미 표시되어 있지 않은 경우 Projects 탐색 모음의 프로젝트 메뉴에서 원하는 프로젝트를 선택합니다.

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

2

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

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

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

  1. cluster의 Browse Collections 버튼을 클릭합니다.

  2. 데이터베이스를 확장하고 컬렉션을 선택합니다.

  3. 컬렉션의 Search Indexes 탭을 클릭합니다.

  1. 클러스터의 이름을 클릭합니다.

  2. Atlas Search 탭을 클릭합니다.

3

쿼리할 인덱스 오른쪽에 있는 Query 버튼을 클릭합니다.

4

JSON 형식의 기본 쿼리 구문 샘플을 보려면 Edit Query 을 클릭합니다.

5

이 쿼리는 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

  • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

  • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

  • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.

[
{
$search: {
"index": "multilingual-tutorial",
"compound": {
"must": [{
"text": {
"query": "Bella",
"path": { "value": "fullplot", "multi": "fullplot_english" }
}
}],
"mustNot": [{
"range": {
"path": "released",
"gt": ISODate("1984-01-01T00:00:00.000Z"),
"lt": ISODate("2016-01-01T00:00:00.000Z")
}
}],
"should": [{
"text": {
"query": "Comedy",
"path": "genres"
}
}]
}
}
}
]
SCORE: 3.909510850906372 _id: "573a1397f29313caabce8bad"
plot: "He is a revenge-obssessed stevedore whose sister was brutally raped an…"
genres:
0: "Drama"
runtime: 137
fullplot: "In Marseilles, a woman commits suicide after she is raped in an alley.…"
released: 1983-05-18T00:00:00.000+00:00
SCORE: 3.4253346920013428 _id: "573a1396f29313caabce5735"
plot: "Giovanna e' una bella ragazza, ma ha qualche problema con gli uomini: …"
genres:
0: "Comedy"
runtime: 100
fullplot: "Giovanna e' una bella ragazza, ma ha qualche problema con gli uomini: …"
released: 1974-11-15T00:00:00.000+00:00
SCORE: 3.363344430923462 _id: "573a1395f29313caabce13cf"
plot: "Gerardo è un attore o almeno cerca di esserlo, ma il pubblico non è de…"
genres:
0: "Comedy"
runtime: 95
fullplot: "Gerardo è un attore o almeno cerca di esserlo, ma il pubblico non è de…"
released: 1960-02-10T00:00:00.000+00:00
SCORE: 1.9502882957458496 _id: "573a1396f29313caabce5299"
plot: "Dr Tremayne is an enigmatic Psychiatrist running a
Futuristic asylum h…"
genres:
0: "Horror"
runtime: 90
fullplot: "Dr Tremayne is an enigmatic Psychiatrist running a Futuristic asylum h…"
released: 1973-10-31T00:00:00.000+00:00
6

Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.

1

터미널 창에서 mongosh 를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh 를 통한 연결을 참조하세요.

2

mongosh 프롬프트에서 다음 명령을 실행합니다.

use sample_mflix
3

이 쿼리는 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

  • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

  • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

  • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

  • title, fullplot, releasedgenres을 제외한 모든 필드 제외

  • 다음과 같은 이름의 필드를 추가합니다. score

db.movies.aggregate([
{
$search: {
"index": "multilingual-tutorial",
"compound": {
"must": [{
"text": {
"path": "fullplot",
"query": "coppia"
}
}],
"mustNot": [{
"range": {
"path": "released",
"gt": ISODate("2000-01-01T00:00:00.000Z"),
"lt": ISODate("2009-01-01T00:00:00.000Z")
}
}],
"should": [{
"text": {
"query": "Drama",
"path": "genres"
}
}]
}
}
},
{
$project: {
"_id": 0,
"title": 1,
"fullplot": 1,
"released": 1,
"genres": 1,
"score": {
"$meta": "searchScore"
}
}
}
])
{
genres: [ 'Drama' ],
title: 'Donzoko',
fullplot: `Una coppia di gretti usurai gestisce uno squallido
dormitorio, nei pressi di una discarica. Una folla di larve e
relitti umani affolla il locale: un ex attore alcolizzato; una
prostituta; un fabbro che sragiona; disoccupati ed altri ancora.
In tutti c'è la ricerca della fuga dalla loro miseranda esistenza,
attraverso alcool, gioco, sogni. Arriva un giorno al dormitorio
un vecchio e saggio pellegrino, che porta in tutti una nota di
speranza con la sua filosofia e la sua umanitè. Ma il sogno dura
poco : lo sconforto torna ad impadronirsi di tutti, al punto da
portare l'ex attore al suicidio e gli altri a ribellarsi ai due
gestori. Ispirato ad un dramma di Gorkij, il film parla della parte
sconfitta dell'umanitè, dei vinti, dei falliti, dei rifiutati
dalla
societè "civile".`,
released: ISODate("1957-10-01T00:00:00.000Z"),
score: 4.606284141540527
},
{
genres: [ 'Mystery', 'Thriller' ],
title: 'Compartiment tueurs',
fullplot: "Sei persone viaggiano in un vagone-letto da Marsiglia a
Parigi. All'arrivo, un donna viene trovata morta nella sua cuccetta.
La polizia si mette alla ricerca delle altre persone, sospettando
possa essere stato uno degli altri cinque passeggeri a commettere
l'omicidio, ma questi sono uccisi uno ad uno. Gli ultimi due (una
coppia di ragazzi conosciutisi per caso nella carrozza) decidono di
cercare di risolvere il caso, per non essere uccisi a loro volta,
rischiando comunque di esserlo. Con il loro aiuto il caso viene
risolto: un giovane e squattrinato studente, amante di una ricca ed
attempata attrice (una delle vittime) ha organizzato gli omicidi
con il suo amante, un giovane poliziotto nevrotico, per derubare la
donna e fuggire insieme in Africa; per cui bisognava uccidere tutti
i componenti del vagone-letto per non destare sospetti. Alla fine,
dopo un inseguimento notturno per le vie di Parigi, lo studente
viene arrestato ed il complice si suicida per non essere catturato.",
released: ISODate("1965-11-17T00:00:00.000Z"),
score: 3.9604406356811523
}
1

터미널 창에서 mongosh 를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh 를 통한 연결을 참조하세요.

2

mongosh 프롬프트에서 다음 명령을 실행합니다.

use sample_mflix
3

이 쿼리는 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

  • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

  • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

  • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

  • title, fullplot, releasedgenres을 제외한 모든 필드 제외

  • 다음과 같은 이름의 필드를 추가합니다. score

db.movies.aggregate([
{
$search: {
"index": "multilingual-tutorial",
"compound": {
"must": [{
"text": {
"query": "Bella",
"path": { "value": "fullplot", "multi": "fullplot_english" }
}
}],
"mustNot": [{
"range": {
"path": "released",
"gt": ISODate("1984-01-01T00:00:00.000Z"),
"lt": ISODate("2016-01-01T00:00:00.000Z")
}
}],
"should": [{
"text": {
"query": "Comedy",
"path": "genres"
}
}]
}
}
},
{
$project: {
"_id": 0,
"title": 1,
"fullplot": 1,
"released": 1,
"genres": 1,
"score": {
"$meta": "searchScore"
}
}
}
])
{
genres: [ 'Drama' ],
title: 'The Moon in the Gutter',
fullplot: "In Marseilles, a woman commits suicide after she is
raped in an alley. Nightly, her brother Gerard broods at the scene
hoping to catch the rapist. He lives with his lover Bella whom he
neglects, an alcoholic brother who lurks about, and his father who's
stayed drunk since the daughter's death, ignoring work and his own
companion. At a seedy bar, Gerard meets a wealthy, nihilistic
hedonist and his beautiful sister. Gerard flips for her and thinks
she's his ticket out of the slum. Bella warns him otherwise and also,
in jealousy, sets two thugs on him. Then Gerard thinks he's found
his sister's rapist. These emotional crises force Gerard to
choose what's most important.",
released: ISODate("1983-05-18T00:00:00.000Z"),
score: 3.909510850906372
},
{
genres: [ 'Comedy' ],
title: 'Policewoman',
fullplot: "Giovanna e' una bella ragazza, ma ha qualche problema
con gli uomini: tutti la vogliono solo usare, anche il suo fidanzata
Claudio. Trovera' una via d'uscita diventando vigile urbano. Come
Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno
e con l'aiuto del pretore Patane', innamorato di lei, smascherera'
una serie di intrallazzi e corruzione denunciando perfino il suo
capo, Marcellini. I due paladini della giustizia coroneranno il
loro sogno d'amore, trasferiti in una lontana isoletta a sud della
Sicilia, ma i corrotti resteranno al loro posto.",
released: ISODate("1974-11-15T00:00:00.000Z"),
score: 3.4253346920013428
},
{
genres: [ 'Comedy' ],
title: 'Love and Larceny',
fullplot: `Gerardo è un attore o almeno cerca di esserlo, ma il
pubblico non è del suo parere. Cosè, per arrotondare gli
introiti, aiuta l'amico Lallo in un suo "lavoretto". Questo gli
costa perè la prigione, dove incontra Chinotto e Gloria Patri.
Uscito inizia, con l'opposizione di Annalisa che lo vuole sposare,
una carriera come truffatore, dapprima in societè con Chinotto e
quindi con la bella Elena. Tutto sembra filare a gonfie vele, e le
truffe divengono sempre piè grosse e di successo. Ma a volte è
destino che il ragno resti preso dalla stessa tela che tesse.`,
released: ISODate("1960-02-10T00:00:00.000Z"),
score: 3.363344430923462
},
{
genres: [ 'Horror' ],
title: 'Tales That Witness Madness',
fullplot: "Dr Tremayne is an enigmatic Psychiatrist running a
Futuristic asylum housing four very special cases. Visited by
colleague Nicholas, Tremayne explains his amazing and controversial
theories as to why each of the four patients went mad... cue four
distinct tales each with a different set of characters: 'Mr
Tiger' tells of Paul, the sensitive and troubled young son of
prosperous but constantly bickering and unlovely parents, and the
boy's 'imaginary' friend, a tiger. 'Penny Farthing' tells of Timothy,
an antique store owner propelled backwards in time by a
penny-farthing bicycle in his shop, all the while being watched over
by the constantly changing photograph of Uncle Albert, which endangers
the lives of both Timothy and his beautiful wife, Ann. 'Mel' tells of
Brian, a man who brings home an old dead tree and prominently
displays it in his living room as a work of art. His fiery wife Bella
soon becomes jealous of the tree, which the husband has lovingly
named Mel, and it seems to be developing a will of its own. 'Luau'
tells of Auriol, a flamboyant and ambitious literary agent who will
do anything to impress her sinister new client, though he seems more
interested in Auriol's beautiful and precocious young daughter Ginny.
Ginny sneaks off on holiday while Auriol plans a sumptuous feast
for her client.",
released: ISODate("1973-10-31T00:00:00.000Z"),
score: 1.9502882957458496
}
1

MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.

2

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

3

이 쿼리는 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

  • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

  • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

  • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

  • title, fullplot, releasedgenres을 제외한 모든 필드 제외

  • 다음과 같은 이름의 필드를 추가합니다. score

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

  1. Aggregations 탭을 클릭합니다.

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

    파이프라인 단계
    쿼리
    $search
    {
    "index": "multilingual-tutorial",
    "compound": {
    "must": [{
    "text": {
    "path": "fullplot",
    "query": "coppia"
    }
    }],
    "mustNot": [{
    "range": {
    "path": "released",
    "gt": ISODate("2000-01-01T00:00:00.000Z"),
    "lt": ISODate("2009-01-01T00:00:00.000Z")
    }
    }],
    "should": [{
    "text": {
    "query": "Drama",
    "path": "genres"
    }
    }]
    }
    }
    $project
    {
    "_id": 0,
    "title": 1,
    "fullplot": 1,
    "released": 1,
    "genres": 1,
    "score": {
    "$meta": "searchScore"
    }
    }

Auto Preview를 활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

{
genres: [ 'Drama' ],
title: 'Donzoko',
fullplot: `Una coppia di gretti usurai gestisce uno squallido
dormitorio, nei pressi di una discarica. Una folla di larve e
relitti umani affolla il locale: un ex attore alcolizzato; una
prostituta; un fabbro che sragiona; disoccupati ed altri ancora.
In tutti c'è la ricerca della fuga dalla loro miseranda esistenza,
attraverso alcool, gioco, sogni. Arriva un giorno al dormitorio
un vecchio e saggio pellegrino, che porta in tutti una nota di
speranza con la sua filosofia e la sua umanitè. Ma il sogno dura
poco : lo sconforto torna ad impadronirsi di tutti, al punto da
portare l'ex attore al suicidio e gli altri a ribellarsi ai due
gestori. Ispirato ad un dramma di Gorkij, il film parla della parte
sconfitta dell'umanitè, dei vinti, dei falliti, dei rifiutati
dalla societè "civile".`,
released: ISODate("1957-10-01T00:00:00.000Z"),
score: 4.606284141540527
},
{
genres: [ 'Mystery', 'Thriller' ],
title: 'Compartiment tueurs',
fullplot: "Sei persone viaggiano in un vagone-letto da Marsiglia a
Parigi. All'arrivo, un donna viene trovata morta nella sua cuccetta.
La polizia si mette alla ricerca delle altre persone, sospettando
possa essere stato uno degli altri cinque passeggeri a commettere
l'omicidio, ma questi sono uccisi uno ad uno. Gli ultimi due (una
coppia di ragazzi conosciutisi per caso nella carrozza) decidono di
cercare di risolvere il caso, per non essere uccisi a loro volta,
rischiando comunque di esserlo. Con il loro aiuto il caso viene
risolto: un giovane e squattrinato studente, amante di una ricca ed
attempata attrice (una delle vittime) ha organizzato gli omicidi
con il suo amante, un giovane poliziotto nevrotico, per derubare la
donna e fuggire insieme in Africa; per cui bisognava uccidere tutti
i componenti del vagone-letto per non destare sospetti. Alla fine,
dopo un inseguimento notturno per le vie di Parigi, lo studente
viene arrestato ed il complice si suicida per non essere catturato.",
released: ISODate("1965-11-17T00:00:00.000Z"),
score: 3.9604406356811523
}
1

MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.

2

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

3

이 쿼리는 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

  • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

  • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

  • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

  • title, fullplot, releasedgenres을 제외한 모든 필드 제외

  • 다음과 같은 이름의 필드를 추가합니다. score

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

  1. Aggregations 탭을 클릭합니다.

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

    파이프라인 단계
    쿼리
    $search
    {
    "index": "multilingual-tutorial",
    "compound": {
    "must": [{
    "text": {
    "path": {"value": "fullplot", "multi": "fullplot_english"},
    "query": "Bella"
    }
    }],
    "mustNot": [{
    "range": {
    "path": "released",
    "gt": ISODate("1984-01-01T00:00:00.000Z"),
    "lt": ISODate("2016-01-01T00:00:00.000Z")
    }
    }],
    "should": [{
    "text": {
    "query": "Comedy",
    "path": "genres"
    }
    }]
    }
    }
    $project
    {
    "_id": 0,
    "title": 1,
    "fullplot": 1,
    "released": 1,
    "genres": 1,
    "score": {
    "$meta": "searchScore"
    }
    }

Auto Preview를 활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

{
genres: [ 'Drama' ],
title: 'The Moon in the Gutter',
fullplot: "In Marseilles, a woman commits suicide after she is
raped in an alley. Nightly, her brother Gerard broods at the scene
hoping to catch the rapist. He lives with his lover Bella whom he
neglects, an alcoholic brother who lurks about, and his father who's
stayed drunk since the daughter's death, ignoring work and his own
companion. At a seedy bar, Gerard meets a wealthy, nihilistic
hedonist and his beautiful sister. Gerard flips for her and thinks
she's his ticket out of the slum. Bella warns him otherwise and also,
in jealousy, sets two thugs on him. Then Gerard thinks he's found
his sister's rapist. These emotional crises force Gerard to
choose what's most important.",
released: ISODate("1983-05-18T00:00:00.000Z"),
score: 3.909510850906372
},
{
genres: [ 'Comedy' ],
title: 'Policewoman',
fullplot: "Giovanna e' una bella ragazza, ma ha qualche problema
con gli uomini: tutti la vogliono solo usare, anche il suo fidanzata
Claudio. Trovera' una via d'uscita diventando vigile urbano. Come
Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno
e con l'aiuto del pretore Patane', innamorato di lei, smascherera'
una serie di intrallazzi e corruzione denunciando perfino il suo
capo, Marcellini. I due paladini della giustizia coroneranno il
loro sogno d'amore, trasferiti in una lontana isoletta a sud della
Sicilia, ma i corrotti resteranno al loro posto.",
released: ISODate("1974-11-15T00:00:00.000Z"),
score: 3.4253346920013428
},
{
genres: [ 'Comedy' ],
title: 'Love and Larceny',
fullplot: `Gerardo è un attore o almeno cerca di esserlo, ma il
pubblico non è del suo parere. Cosè, per arrotondare gli
introiti, aiuta l'amico Lallo in un suo "lavoretto". Questo gli
costa perè la prigione, dove incontra Chinotto e Gloria Patri.
Uscito inizia, con l'opposizione di Annalisa che lo vuole sposare,
una carriera come truffatore, dapprima in societè con Chinotto e
quindi con la bella Elena. Tutto sembra filare a gonfie vele, e le
truffe divengono sempre piè grosse e di successo. Ma a volte è
destino che il ragno resti preso dalla stessa tela che tesse.`,
released: ISODate("1960-02-10T00:00:00.000Z"),
score: 3.363344430923462
},
{
genres: [ 'Horror' ],
title: 'Tales That Witness Madness',
fullplot: "Dr Tremayne is an enigmatic Psychiatrist running a
Futuristic asylum housing four very special cases. Visited by
colleague Nicholas, Tremayne explains his amazing and controversial
theories as to why each of the four patients went mad... cue four
distinct tales each with a different set of characters: 'Mr
Tiger' tells of Paul, the sensitive and troubled young son of
prosperous but constantly bickering and unlovely parents, and the
boy's 'imaginary' friend, a tiger. 'Penny Farthing' tells of Timothy,
an antique store owner propelled backwards in time by a
penny-farthing bicycle in his shop, all the while being watched over
by the constantly changing photograph of Uncle Albert, which endangers
the lives of both Timothy and his beautiful wife, Ann. 'Mel' tells of
Brian, a man who brings home an old dead tree and prominently
displays it in his living room as a work of art. His fiery wife Bella
soon becomes jealous of the tree, which the husband has lovingly
named Mel, and it seems to be developing a will of its own. 'Luau'
tells of Auriol, a flamboyant and ambitious literary agent who will
do anything to impress her sinister new client, though he seems more
interested in Auriol's beautiful and precocious young daughter Ginny.
Ginny sneaks off on holiday while Auriol plans a sumptuous feast
for her client.",
released: ISODate("1973-10-31T00:00:00.000Z"),
score: 1.9502882957458496
}
1
  1. one-language-example 이라는 새 디렉토리를 만들고 dotnet new 명령으로 프로젝트를 초기화합니다.

    mkdir one-language-example
    cd one-language-example
    dotnet new console
  2. .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
2
  1. Program.cs 파일의 내용을 다음 코드로 바꿉니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

      • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class OneLanguageExample
    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(2000, 01, 01, 0, 0, 0, DateTimeKind.Utc);
    24 var endDate = new DateTime(2009, 01, 01, 0, 0, 0, DateTimeKind.Utc);
    25
    26 // define and run pipeline
    27 var results = moviesCollection.Aggregate()
    28 .Search(Builders<MovieDocument>.Search.Compound()
    29 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Fullplot, "coppia"))
    30 .MustNot(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate)))
    31 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Drama")),
    32 indexName: "multilingual-tutorial")
    33 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    34 .Include(movie => movie.Fullplot)
    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 .ToList();
    41
    42 // print results
    43 foreach (var movie in results)
    44 {
    45 Console.WriteLine(movie.ToJson());
    46 }
    47 }
    48}
    49
    50[BsonIgnoreExtraElements]
    51public class MovieDocument
    52{
    53 public string Fullplot { get; set; }
    54 [BsonIgnoreIfDefault]
    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}
  2. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

3
dotnet run one-language-example.csproj
{
"fullplot" : "Una coppia di gretti usurai gestisce uno squallido
dormitorio, nei pressi di una discarica. Una folla di larve e
relitti umani affolla il locale: un ex attore alcolizzato; una
prostituta; un fabbro che sragiona; disoccupati ed altri ancora. In
tutti c'è la ricerca della fuga dalla loro miseranda esistenza,
attraverso alcool, gioco, sogni. Arriva un giorno al dormitorio un
vecchio e saggio pellegrino, che porta in tutti una nota di speranza
con la sua filosofia e la sua umanitè. Ma il sogno dura poco : lo
sconforto torna ad impadronirsi di tutti, al punto da portare l'ex
attore al suicidio e gli altri a ribellarsi ai due gestori. Ispirato
ad un dramma di Gorkij, il film parla della parte sconfitta
dell'umanitè, dei vinti, dei falliti, dei rifiutati dalla societè
\"civile\".",
"genres" : ["Drama"],
"released" : ISODate("1957-10-01T00:00:00Z"),
"title" : "Donzoko",
"score" : 4.6062841415405273
}
{
"fullplot" : "Sei persone viaggiano in un vagone-letto da Marsiglia
a Parigi. All'arrivo, un donna viene trovata morta nella sua
cuccetta. La polizia si mette alla ricerca delle altre persone,
sospettando possa essere stato uno degli altri cinque passeggeri a
commettere l'omicidio, ma questi sono uccisi uno ad uno. Gli ultimi
due (una coppia di ragazzi conosciutisi per caso nella carrozza)
decidono di cercare di risolvere il caso, per non essere uccisi a
loro volta, rischiando comunque di esserlo. Con il loro aiuto il
caso viene risolto: un giovane e squattrinato studente, amante di
una ricca ed attempata attrice (una delle vittime) ha organizzato
gli omicidi con il suo amante, un giovane poliziotto nevrotico, per
derubare la donna e fuggire insieme in Africa; per cui bisognava
uccidere tutti i componenti del vagone-letto per non destare
sospetti. Alla fine, dopo un inseguimento notturno per le vie di
Parigi, lo studente viene arrestato ed il complice si suicida per
non essere catturato.",
"genres" : ["Mystery", "Thriller"],
"released" : ISODate("1965-11-17T00:00:00Z"),
"title" : "Compartiment tueurs",
"score" : 3.9604406356811523
}
1
  1. two-languages-example 이라는 새 디렉토리를 만들고 dotnet new 명령으로 프로젝트를 초기화합니다.

    mkdir two-languages-example
    cd two-languages-example
    dotnet new console
  2. .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
2
  1. Program.cs 파일의 내용을 다음 코드로 바꿉니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

      • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class TwoLanguagesExample
    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(1984, 01, 01, 0, 0, 0, DateTimeKind.Utc);
    24 var endDate = new DateTime(2016, 01, 01, 0, 0, 0, DateTimeKind.Utc);
    25
    26 // define and run pipeline
    27 var results = moviesCollection.Aggregate()
    28 .Search(Builders<MovieDocument>.Search.Compound()
    29 .Must(Builders<MovieDocument>.Search.Text(Builders<MovieDocument>.SearchPath.Analyzer(movie => movie.Fullplot, "fullplot_english"), "Bella"))
    30 .MustNot(Builders<MovieDocument>.Search.Range(movie => movie.Released, SearchRangeBuilder.Gt(startDate).Lt(endDate)))
    31 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy")),
    32 indexName: "multilingual-tutorial")
    33 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    34 .Include(movie => movie.Fullplot)
    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 .ToList();
    41
    42 // print results
    43 foreach (var movie in results)
    44 {
    45 Console.WriteLine(movie.ToJson());
    46 }
    47 }
    48}
    49
    50[BsonIgnoreExtraElements]
    51public class MovieDocument
    52{
    53 public string Fullplot { get; set; }
    54 [BsonIgnoreIfDefault]
    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}
  2. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

3
dotnet run two-languages-example.csproj
{
"fullplot" : "In Marseilles, a woman commits suicide after she is
raped in an alley. Nightly, her brother Gerard broods at the scene
hoping to catch the rapist. He lives with his lover Bella whom he
neglects, an alcoholic brother who lurks about, and his father who's
stayed drunk since the daughter's death, ignoring work and his own
companion. At a seedy bar, Gerard meets a wealthy, nihilistic hedonist
and his beautiful sister. Gerard flips for her and thinks she's his
ticket out of the slum. Bella warns him otherwise and also, in
jealousy, sets two thugs on him. Then Gerard thinks he's found his
sister's rapist. These emotional crises force Gerard to choose what's
most important.",
"genres" : ["Drama"],
"released" : ISODate("1983-05-18T00:00:00Z"),
"title" : "The Moon in the Gutter",
"score" : 3.9095108509063721
}
{
"fullplot" : "Giovanna e' una bella ragazza, ma ha qualche problema
con gli uomini: tutti la vogliono solo usare, anche il suo fidanzata
Claudio. Trovera' una via d'uscita diventando vigile urbano. Come
Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno e con
l'aiuto del pretore Patane', innamorato di lei, smascherera' una serie
di intrallazzi e corruzione denunciando perfino il suo capo,
Marcellini. I due paladini della giustizia coroneranno il loro sogno
d'amore, trasferiti in una lontana isoletta a sud della Sicilia, ma i
corrotti resteranno al loro posto.",
"genres" : ["Comedy"],
"released" : ISODate("1974-11-15T00:00:00Z"),
"title" : "Policewoman",
"score" : 3.4253346920013428
}
{
"fullplot" : "Gerardo è un attore o almeno cerca di esserlo, ma il
pubblico non è del suo parere. Cosè, per arrotondare gli introiti,
aiuta l'amico Lallo in un suo \"lavoretto\". Questo gli costa perè la
prigione, dove incontra Chinotto e Gloria Patri. Uscito inizia, con
l'opposizione di Annalisa che lo vuole sposare, una carriera come
truffatore, dapprima in societè con Chinotto e quindi con la bella
Elena. Tutto sembra filare a gonfie vele, e le truffe divengono sempre
piè grosse e di successo. Ma a volte è destino che il ragno resti
preso dalla stessa tela che tesse.",
"genres" : ["Comedy"],
"released" : ISODate("1960-02-10T00:00:00Z"),
"title" : "Love and Larceny",
"score" : 3.3633444309234619
}
{
"fullplot" : "Dr Tremayne is an enigmatic Psychiatrist running a
Futuristic asylum housing four very special cases. Visited by
colleague Nicholas, Tremayne explains his amazing and controversial
theories as to why each of the four patients went mad... cue four
distinct tales each with a different set of characters: 'Mr Tiger'
tells of Paul, the sensitive and troubled young son of prosperous but
constantly bickering and unlovely parents, and the boy's 'imaginary'
friend, a tiger. 'Penny Farthing' tells of Timothy, an antique store
owner propelled backwards in time by a penny-farthing bicycle in his
shop, all the while being watched over by the constantly changing
photograph of Uncle Albert, which endangers the lives of both Timothy
and his beautiful wife, Ann. 'Mel' tells of Brian, a man who brings
home an old dead tree and prominently displays it in his living room
as a work of art. His fiery wife Bella soon becomes jealous of the
tree, which the husband has lovingly named Mel, and it seems to be
developing a will of its own. 'Luau' tells of Auriol, a flamboyant and
ambitious literary agent who will do anything to impress her sinister
new client, though he seems more interested in Auriol's beautiful and
precocious young daughter Ginny. Ginny sneaks off on holiday while
Auriol plans a sumptuous feast for her client.",
"genres" : ["Horror"],
"released" : ISODate("1973-10-31T00:00:00Z"),
"title" : "Tales That Witness Madness",
"score" : 1.9502882957458496
}
1
  1. one-language-query.go이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 one-language-query.go 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

      • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{"$search", bson.M{
    26 "index": "multilingual-tutorial",
    27 "compound": bson.M{
    28 "must": bson.D{
    29 {"text", bson.M{
    30 "path": "fullplot", "query": "coppia",
    31 }}},
    32 "mustNot": bson.M{
    33 "range": bson.M{
    34 "path": "released",
    35 "gt": time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC),
    36 "lt": time.Date(2009, time.January, 1, 0, 0, 0, 0, time.UTC),
    37 }},
    38 "should": bson.D{
    39 {"text", bson.M{
    40 "path": "genres", "query": "Drama",
    41 }}},
    42 }}}}
    43 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"fullplot", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    44
    45 // run pipeline
    46 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
    47 if err != nil {
    48 panic(err)
    49 }
    50
    51 // print results
    52 var results []bson.D
    53 if err = cursor.All(context.TODO(), &results); err != nil {
    54 panic(err)
    55 }
    56 for _, result := range results {
    57 fmt.Println(result)
    58 }
    59}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    go run one-language-query.go
    [
    {genres [Drama]}
    {title Donzoko}
    {fullplot Una coppia di gretti usurai gestisce uno squallido
    dormitorio, nei pressi di una discarica. Una folla di larve e
    relitti umani affolla il locale: un ex attore alcolizzato; una
    prostituta; un fabbro che sragiona; disoccupati ed altri ancora.
    In tutti c'è la ricerca della fuga dalla loro miseranda
    esistenza, attraverso alcool, gioco, sogni. Arriva un giorno al
    dormitorio un vecchio e saggio pellegrino, che porta in tutti una
    nota di speranza con la sua filosofia e la sua umanitè. Ma il
    sogno dura poco : lo sconforto torna ad impadronirsi di tutti, al
    punto da portare l'ex attore al suicidio e gli altri a ribellarsi
    ai due gestori. Ispirato ad un dramma di Gorkij, il film parla
    della parte sconfitta dell'umanitè, dei vinti, dei falliti, dei
    rifiutati dalla societè "civile".}
    {released -386640000000}
    {score 4.606284141540527}
    ]
    [
    {genres [Mystery Thriller]}
    {title Compartiment tueurs}
    {fullplot Sei persone viaggiano in un vagone-letto da Marsiglia a
    Parigi. All'arrivo, un donna viene trovata morta nella sua
    cuccetta. La polizia si mette alla ricerca delle altre persone,
    sospettando possa essere stato uno degli altri cinque passeggeri
    a commettere l'omicidio, ma questi sono uccisi uno ad uno. Gli
    ultimi due (una coppia di ragazzi conosciutisi per caso nella
    carrozza) decidono di cercare di risolvere il caso, per non
    essere uccisi a loro volta, rischiando comunque di esserlo. Con
    il loro aiuto il caso viene risolto: un giovane e squattrinato
    studente, amante di una ricca ed attempata attrice (una delle
    vittime) ha organizzato gli omicidi con il suo amante, un giovane
    poliziotto nevrotico, per derubare la donna e fuggire insieme in
    Africa; per cui bisognava uccidere tutti i componenti del
    vagone-letto per non destare sospetti. Alla fine, dopo un
    inseguimento notturno per le vie di Parigi, lo studente viene
    arrestato ed il complice si suicida per non essere catturato.}
    {released -130118400000} {score 3.9604406356811523}
    ]
1
  1. two-languages-query.go이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 two-languages-query.go 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

      • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{"$search", bson.M{
    26 "index": "multilingual-tutorial",
    27 "compound": bson.M{
    28 "must": bson.D{
    29 {"text", bson.M{
    30 "path": bson.M{"value": "fullplot", "multi": "fullplot_english"}, "query": "Bella",
    31 }}},
    32 "mustNot": bson.M{
    33 "range": bson.M{
    34 "path": "released",
    35 "gt": time.Date(1984, time.January, 1, 0, 0, 0, 0, time.UTC),
    36 "lt": time.Date(2016, time.January, 1, 0, 0, 0, 0, time.UTC),
    37 }},
    38 "should": bson.D{
    39 {"text", bson.M{
    40 "path": "genres", "query": "Comedy",
    41 }}},
    42 }}}}
    43 projectStage := bson.D{{"$project", bson.D{{"_id", 0}, {"title", 1}, {"fullplot", 1}, {"released", 1}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    44
    45 // run pipeline
    46 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
    47 if err != nil {
    48 panic(err)
    49 }
    50
    51 // print results
    52 var results []bson.D
    53 if err = cursor.All(context.TODO(), &results); err != nil {
    54 panic(err)
    55 }
    56 for _, result := range results {
    57 fmt.Println(result)
    58 }
    59}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    go run two-languages-query.go
    [
    {genres [Drama]}
    {title The Moon in the Gutter}
    {fullplot In Marseilles, a woman commits suicide after she is raped
    in an alley. Nightly, her brother Gerard broods at the scene
    hoping to catch the rapist. He lives with his lover Bella whom he
    neglects, an alcoholic brother who lurks about, and his father
    who's stayed drunk since the daughter's death, ignoring work and his
    own companion. At a seedy bar, Gerard meets a wealthy, nihilistic
    hedonist and his beautiful sister. Gerard flips for her and thinks
    she's his ticket out of the slum. Bella warns him otherwise and
    also, in jealousy, sets two thugs on him. Then Gerard thinks he's
    found his sister's rapist. These emotional crises force Gerard to
    choose what's most important.}
    {released 422064000000}
    {score 3.909510850906372}
    ]
    [
    {genres [Comedy]}
    {title Policewoman}
    {fullplot Giovanna e' una bella ragazza, ma ha qualche problema con
    gli uomini: tutti la vogliono solo usare, anche il suo fidanzata
    Claudio. Trovera' una via d'uscita diventando vigile urbano. Come
    Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno e con
    l'aiuto del pretore Patane', innamorato di lei, smascherera' una serie
    di intrallazzi e corruzione denunciando perfino il suo capo, Marcellini.
    I due paladini della giustizia coroneranno il loro sogno d'amore,
    trasferiti in una lontana isoletta a sud della Sicilia, ma i
    corrotti resteranno al loro posto.}
    {released 153705600000}
    {score 3.4253346920013428}
    ]
    [
    {genres [Comedy]}
    {title Love and Larceny}
    {fullplot Gerardo è un attore o almeno cerca di esserlo, ma il pubblico
    non è del suo parere. Cosè, per arrotondare gli introiti, aiuta l'amico
    Lallo in un suo "lavoretto". Questo gli costa perè la prigione,
    dove incontra Chinotto e Gloria Patri. Uscito inizia, con l'opposizione
    di Annalisa che lo vuole sposare, una carriera come truffatore, dapprima
    in societè con Chinotto e quindi con la bella Elena. Tutto sembra filare
    a gonfie vele, e le truffe divengono sempre piè grosse e di
    successo. Ma a volte è destino che il ragno resti preso dalla stessa
    tela che tesse.}
    {released -312163200000}
    {score 3.363344430923462}
    ]
    [
    {genres [Horror]}
    {title Tales That Witness Madness}
    {fullplot Dr Tremayne is an enigmatic Psychiatrist running a Futuristic
    asylum housing four very special cases. Visited by colleague Nicholas,
    Tremayne explains his amazing and controversial theories as to why each of
    the four patients went mad... cue four distinct tales each with a different
    set of characters: 'Mr Tiger' tells of Paul, the sensitive and troubled
    young son of prosperous but constantly bickering and unlovely parents,
    and the boy's 'imaginary' friend, a tiger. 'Penny Farthing' tells of
    Timothy, an antique store owner propelled backwards in time by a
    penny-farthing bicycle in his shop, all the while being watched over by
    the constantly changing photograph of Uncle Albert, which endangers the
    lives of both Timothy and his beautiful wife, Ann. 'Mel' tells of Brian,
    a man who brings home an old dead tree and prominently displays it in
    his living room as a work of art. His fiery wife Bella soon becomes
    jealous of the tree, which the husband has lovingly named Mel, and it
    seems to be developing a will of its own. 'Luau' tells of Auriol, a
    flamboyant and ambitious literary agent who will do anything to impress
    her sinister new client, though he seems more interested in Auriol's
    beautiful and precocious young daughter Ginny. Ginny sneaks off on
    holiday while Auriol plans a sumptuous feast for her client.}
    {released 120873600000}
    {score 1.9502882957458496}
    ]
1
junit
4.11 또는 그 이상의 버전
mongodb-driver-sync
4.3.0 또는 그 이상의 버전
slf4j-log4j12
1.7.30 또는 그 이상의 버전
2
  1. OneLanguageQuery.java이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 OneLanguageQuery.java 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

      • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1import java.util.Arrays;
    2
    3import static com.mongodb.client.model.Aggregates.project;
    4import static com.mongodb.client.model.Projections.*;
    5import com.mongodb.client.MongoClient;
    6import com.mongodb.client.MongoClients;
    7import com.mongodb.client.MongoCollection;
    8import com.mongodb.client.MongoDatabase;
    9import org.bson.Document;
    10
    11public class OneLanguageQuery {
    12 public static void main( String[] args ) {
    13 // define clauses
    14 List<Document> mustClauses =
    15 List.of( new Document(
    16 "text", new Document("path", "fullplot").append("query", "coppia")));
    17 List<Document> mustNotClauses =
    18 List.of( new Document(
    19 "range", new Document("path", "released")
    20 .append("gt", Date.from(Instant.parse("2000-01-01T00:00:00.000Z")))
    21 .append("lt", Date.from(Instant.parse("2009-01-01T00:00:00.000Z")))));
    22 List<Document> shouldClauses =
    23 List.of(
    24 new Document("text",
    25 new Document("query", "Drama")
    26 .append("path", "genres")));
    27 // define query
    28 Document agg =
    29 new Document( "$search",
    30 new Document( "index", "multilingual-tutorial")
    31 .append("compound",
    32 new Document().append("must", mustClauses)
    33 .append("mustNot", mustNotClauses)
    34 .append("should", shouldClauses)));
    35
    36 // specify connection
    37 String uri = "<connection-string>";
    38
    39 // establish connection and set namespace
    40 try (MongoClient mongoClient = MongoClients.create(uri)) {
    41 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    42 MongoCollection<Document> collection = database.getCollection("movies");
    43
    44 // run query and print results
    45 collection.aggregate(Arrays.asList(agg,
    46 project(fields(
    47 excludeId(),
    48 include("title", "fullplot", "released", "genres"),
    49 computed("score", new Document("$meta", "searchScore"))))))
    50 .forEach(doc -> System.out.println(doc.toJson()));
    51 }
    52 }
    53}

    참고

    Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.

    package com.mongodb.drivers;
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. OneLanguageQuery.java 파일을 컴파일하고 실행합니다.

javac OneLanguageQuery.java
java OneLanguageQuery
{
"genres": ["Drama"],
"title": "Donzoko",
"fullplot":
"Una coppia di gretti usurai gestisce uno squallido dormitorio,
nei pressi di una discarica. Una folla di larve e relitti umani
affolla il locale: un ex attore alcolizzato; una prostituta; un
fabbro che sragiona; disoccupati ed altri ancora. In tutti c'è la
ricerca della fuga dalla loro miseranda esistenza, attraverso
alcool, gioco, sogni. Arriva un giorno al dormitorio un vecchio e
saggio pellegrino, che porta in tutti una nota di speranza con la
sua filosofia e la sua umanitè. Ma il sogno dura poco : lo
sconforto torna ad impadronirsi di tutti, al punto da portare
l'ex attore al suicidio e gli altri a ribellarsi ai due gestori.
Ispirato ad un dramma di Gorkij, il film parla della parte
sconfitta dell'umanitè, dei vinti, dei falliti, dei rifiutati
dalla societè \"civile\".",
"released": {"$date": {"$numberLong": "-386640000000"}},
"score": 4.606284141540527
}
{
"genres": ["Mystery", "Thriller"],
"title": "Compartiment tueurs",
"fullplot":
"Sei persone viaggiano in un vagone-letto da Marsiglia a Parigi.
All'arrivo, un donna viene trovata morta nella sua cuccetta. La
polizia si mette alla ricerca delle altre persone, sospettando
possa essere stato uno degli altri cinque passeggeri a commettere
l'omicidio, ma questi sono uccisi uno ad uno. Gli ultimi due (una
coppia di ragazzi conosciutisi per caso nella carrozza) decidono
di cercare di risolvere il caso, per non essere uccisi a loro
volta, rischiando comunque di esserlo. Con il loro aiuto il caso
viene risolto: un giovane e squattrinato studente, amante di una
ricca ed attempata attrice (una delle vittime) ha organizzato gli
omicidi con il suo amante, un giovane poliziotto nevrotico, per
derubare la donna e fuggire insieme in Africa; per cui bisognava
uccidere tutti i componenti del vagone-letto per non destare
sospetti. Alla fine, dopo un inseguimento notturno per le vie di
Parigi, lo studente viene arrestato ed il complice si suicida per
non essere catturato.",
"released": {"$date": {"$numberLong": "-130118400000"}},
"score": 3.9604406356811523
}
1
junit
4.11 또는 그 이상의 버전
mongodb-driver-sync
4.3.0 또는 그 이상의 버전
slf4j-log4j12
1.7.30 또는 그 이상의 버전
2
  1. TwoLanguagesQuery.java이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 TwoLanguagesQuery.java 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

      • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1import java.util.Arrays;
    2
    3import static com.mongodb.client.model.Aggregates.project;
    4import static com.mongodb.client.model.Projections.*;
    5import com.mongodb.client.MongoClient;
    6import com.mongodb.client.MongoClients;
    7import com.mongodb.client.MongoCollection;
    8import com.mongodb.client.MongoDatabase;
    9import org.bson.Document;
    10
    11public class TwoLanguagesQuery {
    12 public static void main( String[] args ) {
    13 // define clauses
    14 List<Document> mustClauses =
    15 List.of( new Document(
    16 "text", new Document("path", new Document("value", "fullplot").append("multi", "fullplot_english")).append("query", "Bella")));
    17 List<Document> mustNotClauses =
    18 List.of( new Document(
    19 "range", new Document("path", "released")
    20 .append("gt", Date.from(Instant.parse("1984-01-01T00:00:00.000Z")))
    21 .append("lt", Date.from(Instant.parse("2016-01-01T00:00:00.000Z")))));
    22 List<Document> shouldClauses =
    23 List.of(
    24 new Document("text",
    25 new Document("query", "Comedy")
    26 .append("path", "genres")));
    27 // define query
    28 // define query
    29 Document agg =
    30 new Document( "$search",
    31 new Document( "index", "multilingual-tutorial")
    32 .append("compound",
    33 new Document().append("must", mustClauses)
    34 .append("mustNot", mustNotClauses)
    35 .append("should", shouldClauses))));
    36
    37 // specify connection
    38 String uri = "<connection-string>";
    39
    40 // establish connection and set namespace
    41 try (MongoClient mongoClient = MongoClients.create(uri)) {
    42 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    43 MongoCollection<Document> collection = database.getCollection("movies");
    44
    45 // run query and print results
    46 collection.aggregate(Arrays.asList(agg,
    47 project(fields(
    48 excludeId(),
    49 include("title", "fullplot", "released", "genres"),
    50 computed("score", new Document("$meta", "searchScore"))))))
    51 .forEach(doc -> System.out.println(doc.toJson()));
    52 }
    53 }
    54}

    참고

    Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음 코드를 추가합니다.

    package com.mongodb.drivers;
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. TwoLanguagesQuery.java 파일을 컴파일하고 실행합니다.

javac TwoLanguagesQuery.java
java TwoLanguagesQuery
{
"genres": ["Drama"],
"title": "Donzoko",
"fullplot":
"Una coppia di gretti usurai gestisce uno squallido dormitorio,
nei pressi di una discarica. Una folla di larve e relitti umani
affolla il locale: un ex attore alcolizzato; una prostituta; un
fabbro che sragiona; disoccupati ed altri ancora. In tutti c'è la
ricerca della fuga dalla loro miseranda esistenza, attraverso
alcool, gioco, sogni. Arriva un giorno al dormitorio un vecchio e
saggio pellegrino, che porta in tutti una nota di speranza con la
sua filosofia e la sua umanitè. Ma il sogno dura poco : lo
sconforto torna ad impadronirsi di tutti, al punto da portare
l'ex attore al suicidio e gli altri a ribellarsi ai due gestori.
Ispirato ad un dramma di Gorkij, il film parla della parte
sconfitta dell'umanitè, dei vinti, dei falliti, dei rifiutati
dalla societè \"civile\".",
"released": {"$date": {"$numberLong": "-386640000000"}},
"score": 4.606284141540527
}
{
"genres": ["Drama"], "title": "The Moon in the Gutter",
"fullplot":
"In Marseilles, a woman commits suicide after she is
raped in an alley. Nightly, her brother Gerard broods at the scene
hoping to catch the rapist. He lives with his lover Bella whom he
neglects, an alcoholic brother who lurks about, and his father
who's stayed drunk since the daughter's death, ignoring work and
his own companion. At a seedy bar, Gerard meets a wealthy,
nihilistic hedonist and his beautiful sister. Gerard flips for her
and thinks she's his ticket out of the slum. Bella warns him
otherwise and also, in jealousy, sets two thugs on him. Then Gerard
thinks he's found his sister's rapist. These emotional crises force
Gerard to choose what's most important.",
"released": {"$date": "1983-05-18T00:00:00Z"},
"score": 3.909510850906372
}
{
"genres": ["Comedy"],
"title": "Policewoman",
"fullplot":
"Giovanna e' una bella ragazza, ma ha qualche problema con gli
uomini: tutti la vogliono solo usare, anche il suo fidanzata
Claudio. Trovera' una via d'uscita diventando vigile urbano. Come
Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno e
con l'aiuto del pretore Patane', innamorato di lei, smascherera'
una serie di intrallazzi e corruzione denunciando perfino il suo
capo, Marcellini. I due paladini della giustizia coroneranno il
loro sogno d'amore, trasferiti in una lontana isoletta a sud della
Sicilia, ma i corrotti resteranno al loro posto.", "released":
{"$date": "1974-11-15T00:00:00Z"}, "score": 3.4253346920013428}
{"genres": ["Comedy"], "title": "Love and Larceny", "fullplot":
"Gerardo è un attore o almeno cerca di esserlo, ma il pubblico non
è del suo parere. Cosè, per arrotondare gli introiti, aiuta l'amico
Lallo in un suo \"lavoretto\". Questo gli costa perè la prigione,
dove incontra Chinotto e Gloria Patri. Uscito inizia, con
l'opposizione di Annalisa che lo vuole sposare, una carriera come
truffatore, dapprima in societè con Chinotto e quindi con la bella
Elena. Tutto sembra filare a gonfie vele, e le truffe divengono
sempre piè grosse e di successo. Ma a volte è destino che il ragno
resti preso dalla stessa tela che tesse.",
"released": {"$date": {"$numberLong": "-312163200000"}},
"score": 3.363344430923462
}
{
"genres": ["Horror"],
"title": "Tales That Witness Madness",
"fullplot":
"Dr Tremayne is an enigmatic Psychiatrist running a Futuristic
asylum housing four very special cases. Visited by colleague Nicholas,
Tremayne explains his amazing and controversial theories as to why
each of the four patients went mad... cue four distinct tales each
with a different set of characters: 'Mr Tiger' tells of Paul, the
sensitive and troubled young son of prosperous but constantly bickering
and unlovely parents, and the boy's 'imaginary' friend, a tiger. 'Penny
Farthing' tells of Timothy, an antique store owner propelled
backwards in time by a penny-farthing bicycle in his shop, all the while
being watched over by the constantly changing photograph of Uncle Albert,
which endangers the lives of both Timothy and his beautiful wife, Ann.
'Mel' tells of Brian, a man who brings home an old dead tree and
prominently displays it in his living room as a work of art. His
fiery wife Bella soon becomes jealous of the tree, which the husband
has lovingly named Mel, and it seems to be developing a will of its own.
'Luau' tells of Auriol, a flamboyant and ambitious literary agent who
will do anything to impress her sinister new client, though he
seems more interested in Auriol's beautiful and precocious young daughter
Ginny. Ginny sneaks off on holiday while Auriol plans a sumptuous
feast for her client.",
"released": {"$date": "1973-10-31T00:00:00Z"},
"score": 1.9502882957458496
}
1
mongodb-driver-kotlin-coroutine
4.10.0 또는 그 이상의 버전
2
  1. OneLanguageQuery.kt이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 OneLanguageQuery.kt 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

      • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1import com.mongodb.client.model.Aggregates.project
    2import com.mongodb.client.model.Projections.*
    3import com.mongodb.kotlin.client.coroutine.MongoClient
    4import kotlinx.coroutines.runBlocking
    5import org.bson.Document
    6import java.time.Instant
    7import java.util.*
    8
    9fun main() {
    10 // establish connection and set namespace
    11 val uri = "<connection-string>"
    12 val mongoClient = MongoClient.create(uri)
    13
    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 "text", Document("path", "fullplot")
    22 .append("query", "coppia")
    23 )
    24 )
    25
    26 val mustNotClauses = listOf(
    27 Document(
    28 "range",
    29 Document("path", "released")
    30 .append("gt", Date.from(Instant.parse("2000-01-01T00:00:00.000Z")))
    31 .append("lt", Date.from(Instant.parse("2009-01-01T00:00:00.000Z")))
    32 )
    33 )
    34
    35 val shouldClauses = listOf(
    36 Document(
    37 "text",
    38 Document("query", "Drama")
    39 .append("path", "genres")
    40 )
    41 )
    42
    43 // define query
    44 val agg = Document(
    45 "\$search",
    46 Document("index", "multilingual-tutorial")
    47 .append(
    48 "compound",
    49 Document().append("must", mustClauses)
    50 .append("mustNot", mustNotClauses)
    51 .append("should", shouldClauses)
    52 )
    53 )
    54
    55 // run query and print results
    56 val resultsFlow = collection.aggregate<Document>(
    57 listOf(
    58 agg,
    59 project(fields(
    60 excludeId(),
    61 include("title", "fullplot", "released", "genres"),
    62 computed("score", Document("\$meta", "searchScore"))
    63 ))
    64 )
    65 )
    66
    67 resultsFlow.collect { println(it) }
    68 }
    69
    70 mongoClient.close()
    71}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. OneLanguageQuery.kt 파일을 실행합니다.

    IDE에서 OneLanguageQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

    Document{{genres=[Mystery, Thriller], title=Compartiment tueurs, fullplot=Sei persone viaggiano in un vagone-letto da Marsiglia a Parigi. All'arrivo, un donna viene trovata morta nella sua cuccetta. La polizia si mette alla ricerca delle altre persone, sospettando possa essere stato uno degli altri cinque passeggeri a commettere l'omicidio, ma questi sono uccisi uno ad uno. Gli ultimi due (una coppia di ragazzi conosciutisi per caso nella carrozza) decidono di cercare di risolvere il caso, per non essere uccisi a loro volta, rischiando comunque di esserlo. Con il loro aiuto il caso viene risolto: un giovane e squattrinato studente, amante di una ricca ed attempata attrice (una delle vittime) ha organizzato gli omicidi con il suo amante, un giovane poliziotto nevrotico, per derubare la donna e fuggire insieme in Africa; per cui bisognava uccidere tutti i componenti del vagone-letto per non destare sospetti. Alla fine, dopo un inseguimento notturno per le vie di Parigi, lo studente viene arrestato ed il complice si suicida per non essere catturato., released=Tue Nov 16 19:00:00 EST 1965, score=4.068507194519043}}
1
mongodb-driver-kotlin-coroutine
4.10.0 또는 그 이상의 버전
2
  1. TwoLanguagesQuery.kt이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 TwoLanguagesQuery.kt 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas cluster에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

      • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1import com.mongodb.client.model.Aggregates.project
    2import com.mongodb.client.model.Projections.*
    3import com.mongodb.kotlin.client.coroutine.MongoClient
    4import kotlinx.coroutines.runBlocking
    5import org.bson.Document
    6import java.time.Instant
    7import java.util.*
    8
    9fun main() {
    10 // establish connection and set namespace
    11 val uri = "<connection-string>"
    12 val mongoClient = MongoClient.create(uri)
    13
    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 "text",
    22 Document("path", Document("value", "fullplot")
    23 .append("multi", "fullplot_english"))
    24 .append("query", "Bella")
    25 )
    26 )
    27
    28 val mustNotClauses = listOf(
    29 Document(
    30 "range", Document("path", "released")
    31 .append("gt", Date.from(Instant.parse("1984-01-01T00:00:00.000Z")))
    32 .append("lt", Date.from(Instant.parse("2016-01-01T00:00:00.000Z")))
    33 )
    34 )
    35
    36 val shouldClauses = listOf(
    37 Document(
    38 "text",
    39 Document("query", "Comedy")
    40 .append("path", "genres")
    41 )
    42 )
    43
    44 // define query
    45 val agg = Document(
    46 "\$search", Document( "index", "multilingual-tutorial")
    47 .append("compound",
    48 Document().append("must", mustClauses)
    49 .append("mustNot", mustNotClauses)
    50 .append("should", shouldClauses)
    51 )
    52 )
    53
    54 // run query and print results
    55 val resultsFlow = collection.aggregate<Document>(
    56 listOf(
    57 agg,
    58 project(fields(
    59 excludeId(),
    60 include("title", "fullplot", "released", "genres"),
    61 computed("score", Document("\$meta", "searchScore"))
    62 ))
    63 )
    64 )
    65 resultsFlow.collect { println(it) }
    66 }
    67 mongoClient.close()
    68}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. TwoLanguagesQuery.kt 파일을 실행합니다.

    IDE에서 TwoLanguagesQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

    Document{{genres=[Drama], title=The Moon in the Gutter, fullplot=In Marseilles, a woman commits suicide after she is raped in an alley. Nightly, her brother Gerard broods at the scene hoping to catch the rapist. He lives with his lover Bella whom he neglects, an alcoholic brother who lurks about, and his father who's stayed drunk since the daughter's death, ignoring work and his own companion. At a seedy bar, Gerard meets a wealthy, nihilistic hedonist and his beautiful sister. Gerard flips for her and thinks she's his ticket out of the slum. Bella warns him otherwise and also, in jealousy, sets two thugs on him. Then Gerard thinks he's found his sister's rapist. These emotional crises force Gerard to choose what's most important., released=Tue May 17 20:00:00 EDT 1983, score=3.9086267948150635}}
    Document{{genres=[Comedy], title=Policewoman, fullplot=Giovanna e' una bella ragazza, ma ha qualche problema con gli uomini: tutti la vogliono solo usare, anche il suo fidanzata Claudio. Trovera' una via d'uscita diventando vigile urbano. Come Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno e con l'aiuto del pretore Patane', innamorato di lei, smascherera' una serie di intrallazzi e corruzione denunciando perfino il suo capo, Marcellini. I due paladini della giustizia coroneranno il loro sogno d'amore, trasferiti in una lontana isoletta a sud della Sicilia, ma i corrotti resteranno al loro posto., released=Thu Nov 14 19:00:00 EST 1974, score=3.410970687866211}}
    Document{{genres=[Comedy], title=Love and Larceny, fullplot=Gerardo è un attore o almeno cerca di esserlo, ma il pubblico non è del suo parere. Cosè, per arrotondare gli introiti, aiuta l'amico Lallo in un suo "lavoretto". Questo gli costa perè la prigione, dove incontra Chinotto e Gloria Patri. Uscito inizia, con l'opposizione di Annalisa che lo vuole sposare, una carriera come truffatore, dapprima in societè con Chinotto e quindi con la bella Elena. Tutto sembra filare a gonfie vele, e le truffe divengono sempre piè grosse e di successo. Ma a volte è destino che il ragno resti preso dalla stessa tela che tesse., released=Tue Feb 09 19:00:00 EST 1960, score=3.349022388458252}}
    Document{{genres=[Horror], title=Tales That Witness Madness, fullplot=Dr Tremayne is an enigmatic Psychiatrist running a Futuristic asylum housing four very special cases. Visited by colleague Nicholas, Tremayne explains his amazing and controversial theories as to why each of the four patients went mad... cue four distinct tales each with a different set of characters: 'Mr Tiger' tells of Paul, the sensitive and troubled young son of prosperous but constantly bickering and unlovely parents, and the boy's 'imaginary' friend, a tiger. 'Penny Farthing' tells of Timothy, an antique store owner propelled backwards in time by a penny-farthing bicycle in his shop, all the while being watched over by the constantly changing photograph of Uncle Albert, which endangers the lives of both Timothy and his beautiful wife, Ann. 'Mel' tells of Brian, a man who brings home an old dead tree and prominently displays it in his living room as a work of art. His fiery wife Bella soon becomes jealous of the tree, which the husband has lovingly named Mel, and it seems to be developing a will of its own. 'Luau' tells of Auriol, a flamboyant and ambitious literary agent who will do anything to impress her sinister new client, though he seems more interested in Auriol's beautiful and precocious young daughter Ginny. Ginny sneaks off on holiday while Auriol plans a sumptuous feast for her client., released=Tue Oct 30 19:00:00 EST 1973, score=1.9505233764648438}}
1
  1. one-language-query.js이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 one-language-query.js 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • MongoDB의 Node.js 드라이버인 mongodb를 가져옵니다.

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

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

      • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11 await client.connect();
    12
    13 // set namespace
    14 const database = client.db("sample_mflix");
    15 const coll = database.collection("movies");
    16
    17 // define pipeline
    18 const agg = [
    19 { $search: {
    20 index: "multilingual-tutorial",
    21 compound: {
    22 must: [{ text: { path: "fullplot", query: "coppia"} }],
    23 mustNot: [{ range: { path: "released", gt: new Date("2000-01-01T00:00:00.000Z"), lt: new Date("2009-01-01T00:00:00.000Z") } }],
    24 should: [{ text: { query: "Drama", path: "genres" }}]}}},
    25 { $project: {_id: 0, title: 1, fullplot: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}}
    26 ];
    27 // run pipeline
    28 const result = await coll.aggregate(agg);
    29
    30 // print results
    31 await result.forEach((doc) => console.log(doc));
    32 } finally {
    33 await client.close();
    34 }
    35}
    36run().catch(console.dir);
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    node one-language-query.js
    {
    genres: [ 'Drama' ],
    title: 'Donzoko',
    fullplot:
    `Una coppia di gretti usurai gestisce uno squallido dormitorio, nei
    pressi di una discarica. Una folla di larve e relitti umani affolla il
    locale: un ex attore alcolizzato; una prostituta; un fabbro che sragiona;
    disoccupati ed altri ancora. In tutti c\'\xe8 la ricerca della fuga dalla
    loro miseranda esistenza, attraverso alcool, gioco, sogni. Arriva un
    giorno al dormitorio un vecchio e saggio pellegrino, che porta in tutti
    una nota di speranza con la sua filosofia e la sua umanit\xe8. Ma
    il sogno dura poco : lo sconforto torna ad impadronirsi di tutti, al
    punto da portare l\'ex attore al suicidio e gli altri a ribellarsi ai
    due gestori. Ispirato ad un dramma di Gorkij, il film parla della parte
    sconfitta dell\'umanit\xe8, dei vinti, dei falliti, dei rifiutati
    dalla societ\xe8 "civile".`,
    released: 1957-10-01T00:00:00.000Z,
    score: 4.606284141540527
    }
    {
    genres: [ 'Mystery', 'Thriller' ],
    title: 'Compartiment tueurs',
    fullplot:
    "Sei persone viaggiano in un vagone-letto da Marsiglia a Parigi.
    All'arrivo, un donna viene trovata morta nella sua cuccetta. La polizia
    si mette alla ricerca delle altre persone, sospettando possa essere
    stato uno degli altri cinque passeggeri a commettere l'omicidio, ma
    questi sono uccisi uno ad uno. Gli ultimi due (una coppia di ragazzi
    conosciutisi per caso nella carrozza) decidono di cercare di risolvere
    il caso, per non essere uccisi a loro volta, rischiando comunque di
    esserlo. Con il loro aiuto il caso viene risolto: un giovane e
    squattrinato studente, amante di una ricca ed attempata attrice (una
    delle vittime) ha organizzato gli omicidi con il suo amante, un giovane
    poliziotto nevrotico, per derubare la donna e fuggire insieme in Africa;
    per cui bisognava uccidere tutti i componenti del vagone-letto per non
    destare sospetti. Alla fine, dopo un inseguimento notturno per le vie di
    Parigi, lo studente viene arrestato ed il complice si suicida per non
    essere catturato.",
    released: 1965-11-17T00:00:00.000Z,
    score: 3.9604406356811523
    }
1
  1. two-languages-query.js이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 two-languages-query.js 파일에 붙여넣습니다.

    이 코드 예제에서는 다음 작업을 수행합니다:

    • MongoDB의 Node.js 드라이버인 mongodb를 가져옵니다.

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

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

      • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1const { MongoClient } = require("mongodb");
    2
    3// connect to your Atlas cluster
    4const uri =
    5 "<connection-string>";
    6
    7const client = new MongoClient(uri);
    8
    9async function run() {
    10 try {
    11 await client.connect();
    12
    13 // set namespace
    14 const database = client.db("sample_mflix");
    15 const coll = database.collection("movies");
    16
    17 // define pipeline
    18 const agg = [
    19 { $search: {
    20 index: "multilingual-tutorial",
    21 compound: {
    22 must: [{ text: { path: { value: "fullplot", multi: "fullplot_english" }, query: "Bella"} }],
    23 mustNot: [{ range: { path: "released", gt: new Date("1984-01-01T00:00:00.000Z"), lt: new Date("2016-01-01T00:00:00.000Z") } }],
    24 should: [{ text: { query: "Comedy", path: "genres" }}]}}},
    25 { $project: {_id: 0, title: 1, fullplot: 1, released: 1, genres: 1, score: { $meta: "searchScore" }}}
    26 ];
    27 // run pipeline
    28 const result = await coll.aggregate(agg);
    29
    30 // print results
    31 await result.forEach((doc) => console.log(doc));
    32 } finally {
    33 await client.close();
    34 }
    35}
    36run().catch(console.dir);
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    node two-languages-query.js
    {
    genres: [ 'Drama' ],
    title: 'The Moon in the Gutter',
    fullplot: "In Marseilles, a woman commits suicide after she is raped in
    an alley. Nightly, her brother Gerard broods at the scene hoping to catch
    the rapist. He lives with his lover Bella whom he neglects, an alcoholic
    brother who lurks about, and his father who's stayed drunk since the
    daughter's death, ignoring work and his own companion. At a seedy
    bar, Gerard meets a wealthy, nihilistic hedonist and his beautiful sister.
    Gerard flips for her and thinks she's his ticket out of the slum. Bella
    warns him otherwise and also, in jealousy, sets two thugs on him. Then
    Gerard thinks he's found his sister's rapist. These emotional crises force
    Gerard to choose what's most important.",
    released: 1983-05-18T00:00:00.000Z,
    score: 3.909510850906372
    }
    {
    genres: [ 'Comedy' ],
    title: 'Policewoman',
    fullplot: "Giovanna e' una bella ragazza, ma ha qualche problema con gli
    uomini: tutti la vogliono solo usare, anche il suo fidanzata Claudio. Trovera'
    una via d'uscita diventando vigile urbano. Come Giovanna d'Arco, il suo idolo,
    non guardera' in faccia a nessuno e con l'aiuto del pretore Patane',
    innamorato di lei, smascherera' una serie di intrallazzi e
    corruzione denunciando perfino il suo capo, Marcellini. I due paladini
    della giustizia coroneranno il loro sogno d'amore, trasferiti in
    una lontana isoletta a sud della Sicilia, ma i corrotti resteranno al
    loro posto.",
    released: 1974-11-15T00:00:00.000Z,
    score: 3.4253346920013428
    }
    {
    genres: [ 'Comedy' ],
    title: 'Love and Larceny',
    fullplot: `Gerardo è un attore o almeno cerca di esserlo, ma il
    pubblico non è del suo parere. Cosè, per arrotondare gli introiti, aiuta
    l'amico Lallo in un suo "lavoretto". Questo gli costa perè la prigione,
    dove incontra Chinotto e Gloria Patri. Uscito inizia, con
    l'opposizione di Annalisa che lo vuole sposare, una carriera come
    truffatore, dapprima in societè con Chinotto e quindi con la bella Elena.
    Tutto sembra filare a gonfie vele, e le truffe divengono sempre
    piè grosse e di successo. Ma a volte è destino che il ragno resti
    preso dalla stessa tela che tesse.`,
    released: 1960-02-10T00:00:00.000Z,
    score: 3.363344430923462
    }
    {
    genres: [ 'Horror' ],
    title: 'Tales That Witness Madness',
    fullplot: "Dr Tremayne is an enigmatic Psychiatrist running a Futuristic
    asylum housing four very special cases. Visited by colleague Nicholas,
    Tremayne explains his amazing and controversial theories as to
    why each of the four patients went mad... cue four distinct tales each
    with a different set of characters: 'Mr Tiger' tells of Paul, the
    sensitive and troubled young son of prosperous but constantly
    bickering and unlovely parents, and the boy's 'imaginary' friend, a tiger.
    'Penny Farthing' tells of Timothy, an antique store owner propelled
    backwards in time by a penny-farthing bicycle in his shop, all the
    while being watched over by the constantly changing photograph of
    Uncle Albert, which endangers the lives of both Timothy and his beautiful
    wife, Ann. 'Mel' tells of Brian, a man who brings home an old dead tree
    and prominently displays it in his living room as a work of art.
    His fiery wife Bella soon becomes jealous of the tree, which the
    husband has lovingly named Mel, and it seems to be developing a will
    of its own. 'Luau' tells of Auriol, a flamboyant and ambitious literary
    agent who will do anything to impress her sinister new client, though
    he seems more interested in Auriol's beautiful and precocious
    young daughter Ginny. Ginny sneaks off on holiday while Auriol
    plans
    a sumptuous feast for her client.",
    released: 1973-10-31T00:00:00.000Z,
    score: 1.9502882957458496
    }
1
  1. one-language-query.py이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 one-language.py 파일에 붙여넣습니다.

    다음 코드 예제에서는:

    • DNS 시드 목록 연결 문자열을 사용하여 pymongoAtlas 에 연결하는 데 필요한 pymongo, MongoDB의 Python 드라이버 및 dns 모듈을 가져옵니다.

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

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 텍스트 연산자를 사용하여 coppia 이라는 용어가 포함된 이탈리아 영화 줄거리를 검색하는 절

      • mustNot 범위 연산자를 사용하여 2000 년부터 2009 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Drama 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient('<connection-string>')
    6
    7# define pipeline
    8pipeline = [
    9 {"$search": {
    10 "index": "multilingual-tutorial",
    11 "compound": {
    12 "must": [{"text": {"path": "fullplot", "query": "coppia"}}],
    13 "mustNot": [{"range": {"path": "released", "gt": datetime.datetime(2000,1,1,0,0,0), "lt": datetime.datetime(2009,1,1,0,0,0)}}],
    14 "should": [{"text": {"query": "Drama", "path": "genres"}}]}}},
    15 {"$project": {"_id": 0, "title": 1, "fullplot": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}}
    16]
    17# run pipeline
    18result = client["sample_mflix"]["movies"].aggregate(pipeline)
    19
    20# print results
    21for i in result:
    22 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    python one-language.py
    {
    'released': datetime.datetime(1957, 10, 1, 0, 0),
    'genres': ['Drama'],
    'score': 4.606284141540527,
    'fullplot':
    'Una coppia di gretti usurai gestisce uno squallido dormitorio, nei
    pressi di una discarica. Una folla di larve e relitti umani affolla il
    locale: un ex attore alcolizzato; una prostituta; un fabbro che sragiona;
    disoccupati ed altri ancora. In tutti c\'\xe8 la ricerca della fuga dalla
    loro miseranda esistenza, attraverso alcool, gioco, sogni. Arriva un
    giorno al dormitorio un vecchio e saggio pellegrino, che porta in tutti
    una nota di speranza con la sua filosofia e la sua umanit\xe8. Ma
    il sogno dura poco : lo sconforto torna ad impadronirsi di tutti, al
    punto da portare l\'ex attore al suicidio e gli altri a ribellarsi ai
    due gestori. Ispirato ad un dramma di Gorkij, il film parla della parte
    sconfitta dell\'umanit\xe8, dei vinti, dei falliti, dei rifiutati
    dalla societ\xe8 "civile".',
    'title': 'Donzoko'
    }
    {
    'released': datetime.datetime(1965, 11, 17, 0, 0),
    'genres':['Mystery', 'Thriller'],
    'score': 3.9604406356811523,
    'fullplot':
    "Sei persone viaggiano in un vagone-letto da Marsiglia a Parigi.
    All'arrivo, un donna viene trovata morta nella sua cuccetta. La polizia
    si mette alla ricerca delle altre persone, sospettando possa essere
    stato uno degli altri cinque passeggeri a commettere l'omicidio, ma
    questi sono uccisi uno ad uno. Gli ultimi due (una coppia di ragazzi
    conosciutisi per caso nella carrozza) decidono di cercare di risolvere
    il caso, per non essere uccisi a loro volta, rischiando comunque di
    esserlo. Con il loro aiuto il caso viene risolto: un giovane e
    squattrinato studente, amante di una ricca ed attempata attrice (una
    delle vittime) ha organizzato gli omicidi con il suo amante, un giovane
    poliziotto nevrotico, per derubare la donna e fuggire insieme in Africa;
    per cui bisognava uccidere tutti i componenti del vagone-letto per non
    destare sospetti. Alla fine, dopo un inseguimento notturno per le vie di
    Parigi, lo studente viene arrestato ed il complice si suicida per non
    essere catturato.",
    'title': 'Compartiment tueurs'
    }
1
  1. two-languages-query.py이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 two-languages.py 파일에 붙여넣습니다.

    다음 코드 예제에서는:

    • DNS 시드 목록 연결 문자열을 사용하여 pymongoAtlas 에 연결하는 데 필요한 pymongo, MongoDB의 Python 드라이버 및 dns 모듈을 가져옵니다.

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

    • 다음 compound 연산자 절을 사용하여 collection을 쿼리합니다.

      • must 절을 사용하여 텍스트 연산자를 사용하여 용어 Bella 가 포함된 영어 및 이탈리아어로 영화 줄거리를 검색합니다.

      • mustNot 범위 연산자를 사용하여 1984 년부터 2016 년 사이에 개봉된 영화를 제외하는 절

      • should 절을 사용하여 텍스트 연산자를 사용하여 Comedy 장르에 대한 기본 설정을 지정합니다.

      이 쿼리는 $project 파이프라인 단계를 사용하여 다음을 수행합니다.

      • title, fullplot, releasedgenres을 제외한 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. score

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

    1import pymongo
    2import datetime
    3
    4# connect to your Atlas cluster
    5client = pymongo.MongoClient('<connection-string>')
    6
    7# define pipeline
    8pipeline = [
    9 {"$search": {
    10 "index": "multilingual-tutorial",
    11 "compound": {
    12 "must": [{"text": {"path": {"value": "fullplot", "multi": "fullplot_english"}, "query": "Bella"}}],
    13 "mustNot": [{"range": {"path": "released", "gt": datetime.datetime(1984,1,1,0,0,0), "lt": datetime.datetime(2016,1,1,0,0,0)}}],
    14 "should": [{"text": {"query": "Comedy", "path": "genres"}}]}}},
    15 {"$project": {"_id": 0, "title": 1, "fullplot": 1, "released": 1, "genres": 1, "score": {"$meta": "searchScore"}}}
    16]
    17# run pipeline
    18result = client["sample_mflix"]["movies"].aggregate(pipeline)
    19
    20# print results
    21for i in result:
    22 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    python two-languages.py
    {
    'genres': ['Drama'],
    'title': 'The Moon in the Gutter',
    'fullplot': "In Marseilles, a woman commits suicide after she is
    raped in an alley. Nightly, her brother Gerard broods at the scene
    hoping to catch the rapist. He lives with his lover Bella whom he
    neglects, an alcoholic brother who lurks about, and his father who's
    stayed drunk since the daughter's death, ignoring work and his own
    companion. At a seedy bar, Gerard meets a wealthy, nihilistic
    hedonist and his beautiful sister. Gerard flips for her and thinks
    she's his ticket out of the slum. Bella warns him otherwise and also,
    in jealousy, sets two thugs on him. Then Gerard thinks he's found
    his sister's rapist. These emotional crises force Gerard to
    choose what's most important.",
    'released': datetime.datetime(1983, 5, 18, 0, 0),
    'score': 3.909510850906372}
    {
    'genres': ['Comedy'],
    'title': 'Policewoman',
    'fullplot': "Giovanna e' una bella ragazza, ma ha qualche problema
    con gli uomini: tutti la vogliono solo usare, anche il suo fidanzata
    Claudio. Trovera' una via d'uscita diventando vigile urbano. Come
    Giovanna d'Arco, il suo idolo, non guardera' in faccia a nessuno
    e con l'aiuto del pretore Patane', innamorato di lei, smascherera'
    una serie di intrallazzi e corruzione denunciando perfino il suo
    capo, Marcellini. I due paladini della giustizia coroneranno il
    loro sogno d'amore, trasferiti in una lontana isoletta a sud della
    Sicilia, ma i corrotti resteranno al loro posto.",
    'released': datetime.datetime(1974, 11, 15, 0, 0),
    'score': 3.4253346920013428}
    {
    'genres': ['Comedy'],
    'title': 'Love and Larceny',
    'fullplot': 'Gerardo è un attore o almeno cerca di esserlo, ma il
    pubblico non è del suo parere. Cosè, per arrotondare gli
    introiti, aiuta l\'amico Lallo in un suo "lavoretto". Questo gli
    costa perè la prigione, dove incontra Chinotto e Gloria Patri.
    Uscito inizia, con l\'opposizione di Annalisa che lo vuole
    sposare, una carriera come truffatore, dapprima in societè con
    Chinotto e quindi con la bella Elena. Tutto sembra filare a
    gonfie vele, e le truffe divengono sempre piè grosse e di
    successo. Ma a volte è destino che il ragno resti preso dalla
    stessa tela che tesse.',
    'released': datetime.datetime(1960, 2, 10, 0, 0),
    'score': 3.363344430923462}
    {
    'genres': ['Horror'],
    'title': 'Tales That Witness Madness',
    'fullplot': "Dr Tremayne is an enigmatic Psychiatrist running a
    Futuristic asylum housing four very special cases. Visited by
    colleague Nicholas, Tremayne explains his amazing and controversial
    theories as to why each of the four patients went mad... cue four
    distinct tales each with a different set of characters: 'Mr
    Tiger' tells of Paul, the sensitive and troubled young son of
    prosperous but constantly bickering and unlovely parents, and the
    boy's 'imaginary' friend, a tiger. 'Penny Farthing' tells of Timothy,
    an antique store owner propelled backwards in time by a
    penny-farthing bicycle in his shop, all the while being watched over
    by the constantly changing photograph of Uncle Albert, which endangers
    the lives of both Timothy and his beautiful wife, Ann. 'Mel' tells of
    Brian, a man who brings home an old dead tree and prominently
    displays it in his living room as a work of art. His fiery wife Bella
    soon becomes jealous of the tree, which the husband has lovingly
    named Mel, and it seems to be developing a will of its own. 'Luau'
    tells of Auriol, a flamboyant and ambitious literary agent who will
    do anything to impress her sinister new client, though he seems more
    interested in Auriol's beautiful and precocious young daughter Ginny.
    Ginny sneaks off on holiday while Auriol plans a sumptuous feast
    for her client.",
    'released': datetime.datetime(1973, 10, 31, 0, 0),
    'score': 1.9502882957458496}

돌아가기

복합

다음

부분 경기