Docs Menu

날짜 및 숫자 필드에 대해 Atlas Search 문자열 쿼리를 실행하는 방법

이 튜토리얼에서는 sample_airbnb.listingsAndReviews 컬렉션 의 string, datenumber 필드에 대해 Atlas Search 쿼리를 실행하는 방법을 설명합니다. 숫자 및 날짜 필드 값을 문자열로 저장하는 구체화된 뷰를 생성합니다. 그런 다음 구체화된 뷰에 Atlas Search 검색 인덱스를 생성하고 쿼리 문자열자동 완성 연산자를 사용하여 이러한 문자열 필드에 대해 쿼리를 실행합니다. 이 튜토리얼에서는 다음 단계를 안내합니다.

  1. sample_airbnb.listingsAndReviews 컬렉션 name, property_type, last_scrapedaccomodates 필드에 구체화된 뷰를 생성합니다.

  2. 구체화된 뷰에서 동적 및 정적 Atlas Search 검색 인덱스를 설정합니다.

  3. queryString자동 완성 연산자를 사용하여 구체화된 뷰의 필드에 대해 Atlas Search 쿼리를 실행하여 속성을 검색합니다.

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

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

이 섹션에서는 airbnb_listingsAndReviews 컬렉션의 name, property_type, last_scraped, accomodatesmaximum_nights 필드에 대해 airbnb-mat-view 라는 구체화된 뷰 를 생성합니다. 구체화된 뷰를 사용하면 소스 컬렉션의 숫자 및 날짜 필드를 가져와 구체화된 뷰에 문자열 필드로 저장할 수 있습니다.

1

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

2
  1. 다음 명령을 실행하여 클러스터에 데이터베이스가 있는지 확인합니다.

    show dbs
    sample_airbnb 55.3 MB
    sample_analytics 9.59 MB
    sample_geospatial 1.43 MB
    sample_guides 41 kB
    sample_mflix 51.1 MB
    sample_restaurants 6.95 MB
    sample_supplies 1.21 MB
    sample_training 55.5 MB
    sample_weatherdata 2.89 MB
    admin 348 kB
    local 2.1 GB
  2. 다음 명령을 실행하여 sample_airbnb 데이터베이스로 전환합니다.

    use sample_airbnb
    switched to db sample_airbnb
3

구체화된 뷰를 생성하려면 다음 쿼리를 실행합니다. 이 쿼리는 다음 집계 파이프라인 단계를 지정합니다.

  • $project: 이 단계에서 쿼리는 다음을 수행합니다.

    • $dateToString를 사용하여 last_scraped 날짜 객체를 YYYY-MM-DD 형식의 string 로 변환합니다 .

    • nameproperty_type 문자열 필드를 포함합니다.

    • 를 사용하여 숫자 필드를 accomodates string $toString로 변환합니다.

    • 를 사용하여 숫자 필드를 maximum_nights string $toString로 변환합니다.

  • $merge: 이 단계에서 쿼리는 $project 단계의 출력 필드를 airbnb_mat_view라는 구체화된 뷰에 씁니다.

    db.listingsAndReviews.aggregate( [
    {
    $project: {
    lastScrapedDate: { $dateToString: { format: "%Y-%m-%d", date: "$last_scraped" } },
    propertyName: "$name",
    propertyType: "$property_type",
    accommodatesNumber: { $toString: "$accommodates" },
    maximumNumberOfNights: { $toString: "$maximum_nights" }
    }
    },
    { $merge: { into: "airbnb_mat_view", whenMatched: "replace" } }
    ] )
4

확인하려면 다음 명령을 실행합니다.

db.airbnb_mat_view.findOne()
{
_id: '10006546',
lastScrapedDate: '2019-02-16',
propertyName: 'Ribeira Charming Duplex',
propertyType: 'House',
accommodatesNumber: '8',
maximumNumberOfNights: '30'
}

이 섹션에서는 lastScrapedDate, name, propertyType, accommodatesNumbermaximumNumberOfNights 필드에 대해 쿼리를 실행하기 위해 Atlas Search 인덱스를 생성합니다.

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

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

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

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

2

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

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

    참고

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

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

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

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

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

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

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

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

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

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

3
4

페이지에서 다음 항목을 선택한 후 Next를 클릭합니다.

Search Type

Atlas Search 인덱스 유형을 선택합니다.

Index Name and Data Source

다음 정보를 지정합니다.

  • Index Name: date-number-fields-tutorial

  • Database and Collection:

    • sample_airbnb database

    • airbnb_mat_view 컬렉션

Configuration Method

For a guided experience, select Visual Editor.

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

다음 인덱스 중 하나를 생성할 수 있습니다.

  • queryString 연산자를 사용하여 쿼리를 실행하기 위해 동적 매핑을 사용하는 인덱스입니다. 인덱스 정의가 동적 매핑만 사용하는 경우 자동 완성 연산자를 사용하여 쿼리를 실행할 수 없습니다.

  • 자동 완성 연산자를 사용하여 쿼리를 실행하기 위해 정적 매핑을 사용하는 인덱스입니다. autocomplete 유형으로 인덱싱된 필드에 대해서는 queryString 연산자를 사용하여 쿼리를 실행할 수 없습니다.

Atlas 사용자 인터페이스에서 Visual Editor 또는 JSON Editor를 사용하여 인덱스를 생성할 수 있습니다.

Create Search Index를 클릭합니다.

  1. 인덱스 정의를 검토합니다.

    인덱스 정의는 다음과 비슷해야 합니다:

    {
    "mappings": {
    "dynamic": true
    }
    }
  2. Next를 클릭합니다.

  3. Create Search Index를 클릭합니다.

Atlas 사용자 인터페이스에서 Visual Editor 또는 JSON Editor를 사용하여 인덱스를 생성할 수 있습니다.

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

  2. Field Mappings 섹션에서 Add Field을(를) 클릭합니다.

  3. Add Field Mapping 창에서 Customized Configuration을(를) 클릭합니다.

  4. Field Name 드롭다운 메뉴에서 accommodatesNumber을(를) 선택합니다.

  5. Data Type 드롭다운을 클릭하고 드롭다운에서 Autocomplete를 선택한 후 다음 필드를 구성합니다.

    UI 필드 이름
    구성

    Max Grams

    <maximum number of characters to index per sequence, numeric value>

    Min Grams

    <minimum number of characters to index per sequence, numeric value.

    Tokenization

    edgeGram

    Fold Diacritics

    true

    Min Grams에 대한 값이 너무 낮으면 인덱스가 매우 커질 수 있습니다.

  6. Add를 클릭하여 Field Mappings 테이블에 필드를 추가합니다.

  7. Field Mappings 섹션에서 Add Field를 클릭하고 d 단계에서 f 단계를 반복하여 다음 필드에 대한 설정을 구성합니다.

    • lastScrapedDate

    • numberOfNights

  8. Save Changes를 클릭합니다.

  1. 기본 인덱스 정의를 다음 예제 인덱스 정의로 바꿉니다.

    {
    "mappings": {
    "dynamic": false,
    "fields": {
    "accommodatesNumber": [
    {
    "dynamic": true,
    "type": "document"
    },
    {
    "minGrams": 1,
    "type": "autocomplete"
    }
    ],
    "lastScrapedDate": [
    {
    "dynamic": true,
    "type": "document"
    },
    {
    "type": "autocomplete"
    }
    ],
    "maximumNumberOfNights": [
    {
    "dynamic": true,
    "type": "document"
    },
    {
    "minGrams": 1,
    "type": "autocomplete"
    }
    ]
    }
    }
    }
  2. Next를 클릭합니다.

6

Atlas Search에서 인덱스를 빌드하고 있음을 알려주는 You're All Set! 모달 창이 표시됩니다.

7

문자열로 변환된 숫자 및 날짜 필드에 대해 쿼리를 실행할 수 있습니다. 이 튜토리얼에서는 queryString자동 완성 연산자를 사용하여 속성을 검색합니다. 이 쿼리는 다음 파이프라인 단계를 사용합니다.

  • $search 컬렉션을 검색하는 단계

  • $limit 단계는 출력을 5 결과로만 제한합니다.

  • $project 제외할 단계 _id

이 섹션에서는 Atlas 클러스터에 연결하고 airbnb_mat_view 컬렉션의 필드에 대해 연산자를 사용하여 샘플 쿼리를 실행합니다.

참고

구체화된 뷰에서 문자열로 변환된 날짜 및 숫자 필드에 대해서는 근거리 또는 범위 쿼리를 실행할 수 없습니다.


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


1

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

2

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

use sample_airbnb
switched to db sample_airbnb
3

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
1 [
2 {
3 lastScrapedDate: '2019-03-06',
4 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
5 propertyType: 'Condominium',
6 accommodatesNumber: '4'
7 },
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Makaha Valley Paradise with OceanView',
11 propertyType: 'Condominium',
12 accommodatesNumber: '4'
13 },
14 {
15 lastScrapedDate: '2019-03-06',
16 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!',
17 propertyType: 'Condominium',
18 accommodatesNumber: '4'
19 },
20 {
21 lastScrapedDate: '2019-03-06',
22 propertyName: 'Tropical Jungle Oasis',
23 propertyType: 'Condominium',
24 accommodatesNumber: '4'
25 },
26 {
27 lastScrapedDate: '2019-02-11',
28 propertyName: 'Hospede-se com acesso fácil.',
29 propertyType: 'Condominium',
30 accommodatesNumber: '4'
31 }
32 ]
33

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
1 [
2 {
3 lastScrapedDate: '2019-02-11',
4 propertyName: '2017 , férias no Rio',
5 propertyType: 'House',
6 accommodatesNumber: '2',
7 maximumNumberOfNights: '30'
8 },
9 {
10 lastScrapedDate: '2019-03-07',
11 propertyName: 'Newly renovated home',
12 propertyType: 'House',
13 accommodatesNumber: '2',
14 maximumNumberOfNights: '30'
15 },
16 {
17 lastScrapedDate: '2019-02-18',
18 propertyName: 'Vintage House For Rent',
19 propertyType: 'House',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '30'
22 },
23 {
24 lastScrapedDate: '2019-02-18',
25 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev',
26 propertyType: 'House',
27 accommodatesNumber: '2',
28 maximumNumberOfNights: '30'
29 },
30 {
31 lastScrapedDate: '2019-02-16',
32 propertyName: '22 Oporto Guesthouse Cordoaria',
33 propertyType: 'House',
34 accommodatesNumber: '2',
35 maximumNumberOfNights: '30'
36 }
37

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "lastScrapedDate",
"query": "2"
}
},
{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "1"
}
}]
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
[
{
lastScrapedDate: '2019-02-11',
propertyName: 'Horto flat with small garden',
propertyType: 'Apartment',
accommodatesNumber: '4',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-03-06',
propertyName: 'Private Room in Bushwick',
propertyType: 'Apartment',
accommodatesNumber: '1',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-02-11',
propertyName: 'Apt Linda Vista Lagoa - Rio',
propertyType: 'Apartment',
accommodatesNumber: '2',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-02-18',
propertyName: 'Charming Flat in Downtown Moda',
propertyType: 'House',
accommodatesNumber: '6',
maximumNumberOfNights: '1125'
},
{
lastScrapedDate: '2019-02-11',
propertyName: "Catete's Colonial Big Hause Room B",
propertyType: 'House',
accommodatesNumber: '8',
maximumNumberOfNights: '1125'
}
]

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

db.airbnb_mat_view.aggregate([
{
"$search": {
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "3"
}
},
{
"autocomplete": {
"path": "accommodatesNumber",
"query": "2"
}
}]
}
}
},
{ $limit: 5 },
{
$project: {
"_id": 0
}
}
])
[
{
lastScrapedDate: '2019-03-06',
propertyName: 'Ocean View Waikiki Marina w/prkg',
propertyType: 'Condominium',
accommodatesNumber: '2',
maximumNumberOfNights: '365'
},
{
lastScrapedDate: '2019-03-07',
propertyName: 'New York City - Upper West Side Apt',
propertyType: 'Apartment',
accommodatesNumber: '2',
maximumNumberOfNights: '360'
},
{
lastScrapedDate: '2019-03-07',
propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)',
propertyType: 'Apartment',
accommodatesNumber: '2',
maximumNumberOfNights: '30'
},
{
lastScrapedDate: '2019-03-07',
propertyName: 'Private Room (2) in Guest House at Coogee Beach',
propertyType: 'House',
accommodatesNumber: '2',
maximumNumberOfNights: '365'
},
{
lastScrapedDate: '2019-03-06',
propertyName: '~Ao Lele~ Flying Cloud',
propertyType: 'Treehouse',
accommodatesNumber: '2',
maximumNumberOfNights: '30'
}
]
1

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

2

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

3

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

파이프라인 단계
쿼리

$search

{
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
}
}

$limit

{
5
}

$project

{
"_id": 0
}

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

1 [
2 {
3 lastScrapedDate: '2019-03-06',
4 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
5 propertyType: 'Condominium',
6 accommodatesNumber: '4'
7 },
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Makaha Valley Paradise with OceanView',
11 propertyType: 'Condominium',
12 accommodatesNumber: '4'
13 },
14 {
15 lastScrapedDate: '2019-03-06',
16 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!',
17 propertyType: 'Condominium',
18 accommodatesNumber: '4'
19 },
20 {
21 lastScrapedDate: '2019-03-06',
22 propertyName: 'Tropical Jungle Oasis',
23 propertyType: 'Condominium',
24 accommodatesNumber: '4'
25 },
26 {
27 lastScrapedDate: '2019-02-11',
28 propertyName: 'Hospede-se com acesso fácil.',
29 propertyType: 'Condominium',
30 accommodatesNumber: '4'
31 }
32 ]
33

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

파이프라인 단계
쿼리

$search

{
"index": "date-number-fields-tutorial",
"queryString": {
"defaultPath": "propertyType",
"query": "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
}
}

$limit

{
5
}

$project

{
"_id": 0
}

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

1 [
2 {
3 lastScrapedDate: '2019-02-11',
4 propertyName: '2017 , férias no Rio',
5 propertyType: 'House',
6 accommodatesNumber: '2',
7 maximumNumberOfNights: '30'
8 },
9 {
10 lastScrapedDate: '2019-03-07',
11 propertyName: 'Newly renovated home',
12 propertyType: 'House',
13 accommodatesNumber: '2',
14 maximumNumberOfNights: '30'
15 },
16 {
17 lastScrapedDate: '2019-02-18',
18 propertyName: 'Vintage House For Rent',
19 propertyType: 'House',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '30'
22 },
23 {
24 lastScrapedDate: '2019-02-18',
25 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev',
26 propertyType: 'House',
27 accommodatesNumber: '2',
28 maximumNumberOfNights: '30'
29 },
30 {
31 lastScrapedDate: '2019-02-16',
32 propertyName: '22 Oporto Guesthouse Cordoaria',
33 propertyType: 'House',
34 accommodatesNumber: '2',
35 maximumNumberOfNights: '30'
36 }
37

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

파이프라인 단계
쿼리

$search

{
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "lastScrapedDate",
"query": "2"
}
},
{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "1"
}
}]
}
}

$limit

{
5
}

$project

{
"_id": 0
}

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

1 [
2 {
3 lastScrapedDate: '2019-02-11',
4 propertyName: 'Horto flat with small garden',
5 propertyType: 'Apartment',
6 accommodatesNumber: '4',
7 maximumNumberOfNights: '1125'
8 },
9 {
10 lastScrapedDate: '2019-03-06',
11 propertyName: 'Private Room in Bushwick',
12 propertyType: 'Apartment',
13 accommodatesNumber: '1',
14 maximumNumberOfNights: '1125'
15 },
16 {
17 lastScrapedDate: '2019-02-11',
18 propertyName: 'Apt Linda Vista Lagoa - Rio',
19 propertyType: 'Apartment',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '1125'
22 },
23 {
24 lastScrapedDate: '2019-02-18',
25 propertyName: 'Charming Flat in Downtown Moda',
26 propertyType: 'House',
27 accommodatesNumber: '6',
28 maximumNumberOfNights: '1125'
29 },
30 {
31 lastScrapedDate: '2019-02-11',
32 propertyName: "Catete's Colonial Big Hause Room B",
33 propertyType: 'House',
34 accommodatesNumber: '8',
35 maximumNumberOfNights: '1125'
36 }
37 ]

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

파이프라인 단계
쿼리

$search

{
"index": "date-number-fields-tutorial",
"compound": {
"should": [{
"autocomplete": {
"path": "maximumNumberOfNights",
"query": "3"
}
},
{
"autocomplete": {
"path": "accommodatesNumber",
"query": "2"
}
}]
}
}

$limit

{
5
}

$project

{
"_id": 0
}

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

1[
2 {
3 lastScrapedDate: '2019-03-06',
4 propertyName: 'Ocean View Waikiki Marina w/prkg',
5 propertyType: 'Condominium',
6 accommodatesNumber: '2',
7 maximumNumberOfNights: '365'
8 },
9 {
10 lastScrapedDate: '2019-03-07',
11 propertyName: 'New York City - Upper West Side Apt',
12 propertyType: 'Apartment',
13 accommodatesNumber: '2',
14 maximumNumberOfNights: '360'
15 },
16 {
17 lastScrapedDate: '2019-03-07',
18 propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)',
19 propertyType: 'Apartment',
20 accommodatesNumber: '2',
21 maximumNumberOfNights: '30'
22 },
23 {
24 lastScrapedDate: '2019-03-07',
25 propertyName: 'Private Room (2) in Guest House at Coogee Beach',
26 propertyType: 'House',
27 accommodatesNumber: '2',
28 maximumNumberOfNights: '365'
29 },
30 {
31 lastScrapedDate: '2019-03-06',
32 propertyName: '~Ao Lele~ Flying Cloud',
33 propertyType: 'Treehouse',
34 accommodatesNumber: '2',
35 maximumNumberOfNights: '30'
36 }
37]
1
mkdir date-number-to-string-query
cd date-number-to-string-query
dotnet new console
2
dotnet add package MongoDB.Driver
3

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

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

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

  • Atlas 클러스터에 대한 연결을 설정합니다.

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

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.QueryString(
25 airbnb => airbnb.propertyType,
26 "(Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"
27 ),
28 indexName: "date-number-fields-tutorial")
29 .Limit(5)
30 .Project<matViewDocument>(Builders<matViewDocument>.Projection
31 .Exclude(airbnb => airbnb.Id))
32 .ToList();
33
34 // print results
35 foreach (var airbnb in results)
36 {
37 Console.WriteLine(airbnb.ToJson());
38 }
39 }
40}
41
42[BsonIgnoreExtraElements]
43public class matViewDocument
44{
45 [BsonIgnoreIfDefault]
46 public string Id { get; set; }
47 public string lastScrapedDate { get; set; }
48 public string propertyName { get; set; }
49 public string propertyType { get; set; }
50 public string accommodatesNumber { get; set; }
51 public string maximumNumberOfNights { get; set; }
52}

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

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 var ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.QueryString(
25 airbnb => airbnb.propertyType,
26 "House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
27 ),
28 indexName: "date-number-fields-tutorial")
29 .Limit(5)
30 .Project<matViewDocument>(Builders<matViewDocument>.Projection
31 .Exclude(airbnb => airbnb.Id))
32 .ToList();
33
34 // print results
35 foreach (var airbnb in results)
36 {
37 Console.WriteLine(airbnb.ToJson());
38 }
39 }
40}
41
42[BsonIgnoreExtraElements]
43public class matViewDocument
44{
45 [BsonIgnoreIfDefault]
46 public string Id { get; set; }
47 public string lastScrapedDate { get; set; }
48 public string propertyName { get; set; }
49 public string propertyType { get; set; }
50 public string accommodatesNumber { get; set; }
51 public string maximumNumberOfNights { get; set; }
52}

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

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

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

  • Atlas 클러스터에 대한 연결을 설정합니다.

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

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.Compound()
25 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.lastScrapedDate, "2"))
26 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.maximumNumberOfNights, "1")),
27 indexName: "date-number-fields-tutorial")
28 .Limit(5)
29 .Project<matViewDocument>(Builders<matViewDocument>.Projection
30 .Exclude(airbnb => airbnb.Id))
31 .ToList();
32
33 // print results
34 foreach (var airbnb in results)
35 {
36 Console.WriteLine(airbnb.ToJson());
37 }
38 }
39}
40
41[BsonIgnoreExtraElements]
42public class matViewDocument
43{
44 [BsonIgnoreIfDefault]
45 public string Id { get; set; }
46 public string lastScrapedDate { get; set; }
47 public string propertyName { get; set; }
48 public string propertyType { get; set; }
49 public string accommodatesNumber { get; set; }
50 public string maximumNumberOfNights { get; set; }
51}

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

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class DateNumberToStringQuery
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 airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
20 var matViewCollection = airbnbDatabase.GetCollection<matViewDocument>("airbnb_mat_view");
21
22 // define and run pipeline
23 var results = matViewCollection.Aggregate()
24 .Search(Builders<matViewDocument>.Search.Compound()
25 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.maximumNumberOfNights, "3"))
26 .Should(Builders<matViewDocument>.Search.Autocomplete(airbnb => airbnb.accommodatesNumber, "2")),
27 indexName: "date-number-fields-tutorial")
28 .Limit(5)
29 .Project<matViewDocument>(Builders<matViewDocument>.Projection
30 .Exclude(airbnb => airbnb.Id))
31 .ToList();
32
33 // print results
34 foreach (var airbnb in results)
35 {
36 Console.WriteLine(airbnb.ToJson());
37 }
38 }
39}
40
41[BsonIgnoreExtraElements]
42public class matViewDocument
43{
44 [BsonIgnoreIfDefault]
45 public string Id { get; set; }
46 public string lastScrapedDate { get; set; }
47 public string propertyName { get; set; }
48 public string propertyType { get; set; }
49 public string accommodatesNumber { get; set; }
50 public string maximumNumberOfNights { get; set; }
51}

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

4
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Makaha Valley Paradise with OceanView",
11 "propertyType": "Condominium",
12 "accommodatesNumber": "4",
13 "maximumNumberOfNights": "180"
14}
15{
16 "lastScrapedDate": "2019-03-06",
17 "propertyName": "March 2019 availability! Oceanview on Sugar Beach!",
18 "propertyType": "Condominium",
19 "accommodatesNumber": "4",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-03-06",
24 "propertyName": "Tropical Jungle Oasis",
25 "propertyType": "Condominium",
26 "accommodatesNumber": "4",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Hospede-se com acesso fácil.",
32 "propertyType": "Condominium",
33 "accommodatesNumber": "4",
34 "maximumNumberOfNights": "1125"
35}
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "2017 , férias no Rio",
4 "propertyType": "House",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "30"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "Newly renovated home",
11 "propertyType": "House",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "30"
14}
15{
16 "lastScrapedDate": "2019-02-18",
17 "propertyName": "Vintage House For Rent",
18 "propertyType": "House",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "4floor house in Taksim,Taksimde 4katli müstakil ev",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "30"
28}
29{
30 "lastScrapedDate": "2019-02-16",
31 "propertyName": "22 Oporto Guesthouse Cordoaria",
32 "propertyType": "House",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "Horto flat with small garden",
4 "propertyType": "Apartment",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Private Room in Bushwick",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "1",
13 "maximumNumberOfNights": "1125"
14}
15{
16 "lastScrapedDate": "2019-02-11",
17 "propertyName": "Apt Linda Vista Lagoa - Rio",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "Charming Flat in Downtown Moda",
25 "propertyType": "House",
26 "accommodatesNumber": "6",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Catete's Colonial Big Hause Room B",
32 "propertyType": "House",
33 "accommodatesNumber": "8",
34 "maximumNumberOfNights": "1125"
35}
dotnet run Program.cs
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "Ocean View Waikiki Marina w/prkg",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "365"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "New York City - Upper West Side Apt",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "360"
14}
15{
16 "lastScrapedDate": "2019-03-07",
17 "propertyName": "Sydney Hyde Park City Apartment (checkin from 6am)",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-03-07",
24 "propertyName": "Private Room (2) in Guest House at Coogee Beach",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "365"
28}
29{
30 "lastScrapedDate": "2019-03-06",
31 "propertyName": "~Ao Lele~ Flying Cloud",
32 "propertyType": "Treehouse",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
1
2

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

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 var err error
15 // connect to the Atlas cluster
16 ctx := context.Background()
17 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
18 if err != nil {
19 panic(err)
20 }
21 defer client.Disconnect(ctx)
22 // set namespace
23 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
24 // define pipeline
25 searchStage := bson.D{{"$search", bson.D{
26 {"index", "date-number-fields-tutorial"},
27 {"queryString", bson.D{
28 {"defaultPath", "propertyType"},
29 {"query", "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"},
30 }}}}}
31 limitStage := bson.D{{"$limit", 5}}
32 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
33 // specify the amount of time the operation can run on the server
34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
35 // run pipeline
36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
37 if err != nil {
38 panic(err)
39 }
40 // print results
41 var results []bson.D
42 if err = cursor.All(context.TODO(), &results); err != nil {
43 panic(err)
44 }
45 for _, result := range results {
46 fmt.Println(result)
47 }
48}

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

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

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 var err error
15 // connect to the Atlas cluster
16 ctx := context.Background()
17 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
18 if err != nil {
19 panic(err)
20 }
21 defer client.Disconnect(ctx)
22 // set namespace
23 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
24 // define pipeline
25 searchStage := bson.D{{"$search", bson.D{
26 {"index", "date-number-fields-tutorial"},
27 {"queryString", bson.D{
28 {"defaultPath", "propertyType"},
29 {"query", "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"},
30 }}}}}
31 limitStage := bson.D{{"$limit", 5}}
32 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
33 // specify the amount of time the operation can run on the server
34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
35 // run pipeline
36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
37 if err != nil {
38 panic(err)
39 }
40 // print results
41 var results []bson.D
42 if err = cursor.All(context.TODO(), &results); err != nil {
43 panic(err)
44 }
45 for _, result := range results {
46 fmt.Println(result)
47 }
48}

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

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

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
13// define structure of movies collection
14type MovieCollection struct {
15 title string `bson:"Title,omitempty"`
16}
17
18func main() {
19 var err error
20 // connect to the Atlas cluster
21 ctx := context.Background()
22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-tring>"))
23 if err != nil {
24 panic(err)
25 }
26 defer client.Disconnect(ctx)
27 // set namespace
28 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
29 // define pipeline
30 searchStage := bson.D{{"$search", bson.M{
31 "index": "date-number-fields-tutorial",
32 "compound": bson.M{
33 "should": bson.A{
34 bson.M{
35 "autocomplete": bson.M{
36 "path": "lastScrapedDate", "query": "2",
37 },
38 },
39 bson.M{
40 "autocomplete": bson.M{
41 "path": "maximumNumberOfNights", "query": "1",
42 },
43 },
44 },
45 },
46 }}}
47 limitStage := bson.D{{"$limit", 5}}
48 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
49 // specify the amount of time the operation can run on the server
50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
51 // run pipeline
52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
53 if err != nil {
54 panic(err)
55 }
56 // print results
57 var results []bson.D
58 if err = cursor.All(context.TODO(), &results); err != nil {
59 panic(err)
60 }
61 for _, result := range results {
62 fmt.Println(result)
63 }
64}

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

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

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
13// define structure of movies collection
14type MovieCollection struct {
15 title string `bson:"Title,omitempty"`
16}
17
18func main() {
19 var err error
20 // connect to the Atlas cluster
21 ctx := context.Background()
22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
23 if err != nil {
24 panic(err)
25 }
26 defer client.Disconnect(ctx)
27 // set namespace
28 collection := client.Database("sample_airbnb").Collection("airbnb_mat_view")
29 // define pipeline
30 searchStage := bson.D{{"$search", bson.M{
31 "index": "date-number-fields-tutorial",
32 "compound": bson.M{
33 "should": bson.A{
34 bson.M{
35 "autocomplete": bson.M{
36 "path": "maximumNumberOfNights", "query": "3",
37 },
38 },
39 bson.M{
40 "autocomplete": bson.M{
41 "path": "accommodatesNumber", "query": "2",
42 },
43 },
44 },
45 },
46 }}}
47 limitStage := bson.D{{"$limit", 5}}
48 projectStage := bson.D{{"$project", bson.D{{"_id", 0}}}}
49 // specify the amount of time the operation can run on the server
50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
51 // run pipeline
52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
53 if err != nil {
54 panic(err)
55 }
56 // print results
57 var results []bson.D
58 if err = cursor.All(context.TODO(), &results); err != nil {
59 panic(err)
60 }
61 for _, result := range results {
62 fmt.Println(result)
63 }
64}

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

3
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-03-06}
3 {propertyName LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!}
4 {propertyType Condominium}
5 {accommodatesNumber 4}
6 {maximumNumberOfNights 1125}
7]
8[
9 {lastScrapedDate 2019-03-06}
10 {propertyName Makaha Valley Paradise with OceanView}
11 {propertyType Condominium}
12 {accommodatesNumber 4}
13 {maximumNumberOfNights 180}
14]
15[
16 {lastScrapedDate 2019-03-06}
17 {propertyName March 2019 availability! Oceanview on Sugar Beach!}
18 {propertyType Condominium}
19 {accommodatesNumber 4}
20 {maximumNumberOfNights 1125}
21]
22[
23 {lastScrapedDate 2019-03-06}
24 {propertyName Tropical Jungle Oasis}
25 {propertyType Condominium}
26 {accommodatesNumber 4}
27 {maximumNumberOfNights 1125}
28]
29[
30 {lastScrapedDate 2019-02-11}
31 {propertyName Hospede-se com acesso fácil.}
32 {propertyType Condominium}
33 {accommodatesNumber 4}
34 {maximumNumberOfNights 1125}
35]
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-02-11}
3 {propertyName 2017 , férias no Rio}
4 {propertyType House}
5 {accommodatesNumber 2}
6 {maximumNumberOfNights 30}
7]
8[
9 {lastScrapedDate 2019-03-07}
10 {propertyName Newly renovated home}
11 {propertyType House}
12 {accommodatesNumber 2}
13 {maximumNumberOfNights 30}
14]
15[
16 {lastScrapedDate 2019-02-18}
17 {propertyName Vintage House For Rent}
18 {propertyType House}
19 {accommodatesNumber 2}
20 {maximumNumberOfNights 30}
21]
22[
23 {lastScrapedDate 2019-02-18}
24 {propertyName 4floor house in Taksim,Taksimde 4katli müstakil ev}
25 {propertyType House}
26 {accommodatesNumber 2}
27 {maximumNumberOfNights 30}
28]
29[
30 {lastScrapedDate 2019-02-16}
31 {propertyName 22 Oporto Guesthouse Cordoaria}
32 {propertyType House}
33 {accommodatesNumber 2}
34 {maximumNumberOfNights 30}
35]
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-02-11}
3 {propertyName Horto flat with small garden}
4 {propertyType Apartment}
5 {accommodatesNumber 4}
6 {maximumNumberOfNights 1125}
7]
8[
9 {lastScrapedDate 2019-03-06}
10 {propertyName Private Room in Bushwick}
11 {propertyType Apartment}
12 {accommodatesNumber 1}
13 {maximumNumberOfNights 1125}
14]
15[
16 {lastScrapedDate 2019-02-11}
17 {propertyName Apt Linda Vista Lagoa - Rio}
18 {propertyType Apartment}
19 {accommodatesNumber 2}
20 {maximumNumberOfNights 1125}
21]
22[
23 {lastScrapedDate 2019-02-18}
24 {propertyName Charming Flat in Downtown Moda}
25 {propertyType House}
26 {accommodatesNumber 6}
27 {maximumNumberOfNights 1125}
28]
29[
30 {lastScrapedDate 2019-02-11}
31 {propertyName Catete's Colonial Big Hause Room B}
32 {propertyType House}
33 {accommodatesNumber 8}
34 {maximumNumberOfNights 1125}
35]
go run date-number-to-string-query.go
1[
2 {lastScrapedDate 2019-03-06}
3 {propertyName Ocean View Waikiki Marina w/prkg}
4 {propertyType Condominium}
5 {accommodatesNumber 2}
6 {maximumNumberOfNights 365}
7]
8[
9 {lastScrapedDate 2019-03-07}
10 {propertyName New York City - Upper West Side Apt}
11 {propertyType Apartment}
12 {accommodatesNumber 2}
13 {maximumNumberOfNights 360}
14]
15[
16 {lastScrapedDate 2019-03-07}
17 {propertyName Sydney Hyde Park City Apartment (checkin from 6am)}
18 {propertyType Apartment}
19 {accommodatesNumber 2}
20 {maximumNumberOfNights 30}
21]
22[
23 {lastScrapedDate 2019-03-07}
24 {propertyName Private Room (2) in Guest House at Coogee Beach}
25 {propertyType House}
26 {accommodatesNumber 2}
27 {maximumNumberOfNights 365}
28]
29[
30 {lastScrapedDate 2019-03-06}
31 {propertyName ~Ao Lele~ Flying Cloud}
32 {propertyType Treehouse}
33 {accommodatesNumber 2}
34 {maximumNumberOfNights 30}
35]
1

junit

4.11 또는 그 이상의 버전

mongodb-driver-sync

4.3.0 또는 그 이상의 버전

slf4j-log4j12

1.7.30 또는 그 이상의 버전

2
3

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

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

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

  • Atlas 클러스터에 대한 연결을 설정합니다.

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

참고

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

package com.mongodb.drivers;

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
3import static com.mongodb.client.model.Aggregates.limit;
4import static com.mongodb.client.model.Aggregates.project;
5import static com.mongodb.client.model.Projections.excludeId;
6import static com.mongodb.client.model.Projections.fields;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("queryString",
19 new Document("defaultPath", "propertyType")
20 .append("query", "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019")));
21
22 // specify connection
23 String uri = "<connection-string>";
24
25 // establish connection and set namespace
26 try (MongoClient mongoClient = MongoClients.create(uri)) {
27 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
28 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
29 // run query and print results
30 collection.aggregate(Arrays.asList(agg,
31 limit(5),
32 project(fields(excludeId()) ))
33 ).forEach(doc -> System.out.println(doc.toJson()));
34 }
35 }
36}

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

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
3import static com.mongodb.client.model.Aggregates.limit;
4import static com.mongodb.client.model.Aggregates.project;
5import static com.mongodb.client.model.Projections.excludeId;
6import static com.mongodb.client.model.Projections.fields;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("queryString",
19 new Document("defaultPath", "propertyType")
20 .append("query", "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30")));
21
22 // specify connection
23 String uri = "<connection-string>";
24
25 // establish connection and set namespace
26 try (MongoClient mongoClient = MongoClients.create(uri)) {
27 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
28 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
29 // run query and print results
30 collection.aggregate(Arrays.asList(agg,
31 limit(5),
32 project(fields(excludeId()) ))
33 ).forEach(doc -> System.out.println(doc.toJson()));
34 }
35 }
36}

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

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

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

  • Atlas 클러스터에 대한 연결을 설정합니다.

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

참고

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

package com.mongodb.drivers;

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
3import static com.mongodb.client.model.Aggregates.limit;
4import static com.mongodb.client.model.Aggregates.project;
5import static com.mongodb.client.model.Projections.excludeId;
6import static com.mongodb.client.model.Projections.fields;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("compound",
19 new Document("should", Arrays.asList(
20 new Document("autocomplete",
21 new Document("path", "lastScrapedDate")
22 .append("query", "2")),
23 new Document("autocomplete",
24 new Document("path", "maximumNumberOfNights")
25 .append("query", "1"))))));
26
27 // specify connection
28 String uri = "<connection-string>";
29
30 // establish connection and set namespace
31 try (MongoClient mongoClient = MongoClients.create(uri)) {
32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
33 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
34 // run query and print results
35 collection.aggregate(Arrays.asList(
36 eq("$search", eq("compound", agg)),
37 limit(5),
38 project(fields(excludeId()) ))
39 ).forEach(doc -> System.out.println(doc.toJson()));
40 }
41 }
42}

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

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

1import java.util.Arrays;
2import static com.mongodb.client.model.Filters.eq;
3import static com.mongodb.client.model.Aggregates.limit;
4import static com.mongodb.client.model.Aggregates.project;
5import static com.mongodb.client.model.Projections.excludeId;
6import static com.mongodb.client.model.Projections.fields;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class DateNumberToStringQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg = new Document("$search",
17 new Document ("index", "date-number-fields-tutorial")
18 .append("compound",
19 new Document("should", Arrays.asList(
20 new Document("autocomplete",
21 new Document("path", "maximumNumberOfNights")
22 .append("query", "3")),
23 new Document("autocomplete",
24 new Document("path", "accommodatesNumber")
25 .append("query", "2"))))));
26
27 // specify connection
28 String uri = "<connection-string>";
29
30 // establish connection and set namespace
31 try (MongoClient mongoClient = MongoClients.create(uri)) {
32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
33 MongoCollection<Document> collection = database.getCollection("airbnb_mat_view");
34 // run query and print results
35 collection.aggregate(Arrays.asList(
36 eq("$search", eq("compound", agg)),
37 limit(5),
38 project(fields(excludeId()) ))
39 ).forEach(doc -> System.out.println(doc.toJson()));
40 }
41 }
42}

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

4
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Makaha Valley Paradise with OceanView",
11 "propertyType": "Condominium",
12 "accommodatesNumber": "4",
13 "maximumNumberOfNights": "180"
14}
15{
16 "lastScrapedDate": "2019-03-06",
17 "propertyName": "March 2019 availability! Oceanview on Sugar Beach!",
18 "propertyType": "Condominium",
19 "accommodatesNumber": "4",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-03-06",
24 "propertyName": "Tropical Jungle Oasis",
25 "propertyType": "Condominium",
26 "accommodatesNumber": "4",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Hospede-se com acesso fácil.",
32 "propertyType": "Condominium",
33 "accommodatesNumber": "4",
34 "maximumNumberOfNights": "1125"
35}
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "2017 , férias no Rio",
4 "propertyType": "House",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "30"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "Newly renovated home",
11 "propertyType": "House",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "30"
14}
15{
16 "lastScrapedDate": "2019-02-18",
17 "propertyName": "Vintage House For Rent",
18 "propertyType": "House",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "4floor house in Taksim,Taksimde 4katli müstakil ev",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "30"
28}
29{
30 "lastScrapedDate": "2019-02-16",
31 "propertyName": "22 Oporto Guesthouse Cordoaria",
32 "propertyType": "House",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-02-11",
3 "propertyName": "Horto flat with small garden",
4 "propertyType": "Apartment",
5 "accommodatesNumber": "4",
6 "maximumNumberOfNights": "1125"
7}
8{
9 "lastScrapedDate": "2019-03-06",
10 "propertyName": "Private Room in Bushwick",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "1",
13 "maximumNumberOfNights": "1125"
14}
15{
16 "lastScrapedDate": "2019-02-11",
17 "propertyName": "Apt Linda Vista Lagoa - Rio",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "1125"
21}
22{
23 "lastScrapedDate": "2019-02-18",
24 "propertyName": "Charming Flat in Downtown Moda",
25 "propertyType": "House",
26 "accommodatesNumber": "6",
27 "maximumNumberOfNights": "1125"
28}
29{
30 "lastScrapedDate": "2019-02-11",
31 "propertyName": "Catete's Colonial Big Hause Room B",
32 "propertyType": "House",
33 "accommodatesNumber": "8",
34 "maximumNumberOfNights": "1125"
35}
javac DateNumberToStringQuery.java
java DateNumberToStringQuery
1{
2 "lastScrapedDate": "2019-03-06",
3 "propertyName": "Ocean View Waikiki Marina w/prkg",
4 "propertyType": "Condominium",
5 "accommodatesNumber": "2",
6 "maximumNumberOfNights": "365"
7}
8{
9 "lastScrapedDate": "2019-03-07",
10 "propertyName": "New York City - Upper West Side Apt",
11 "propertyType": "Apartment",
12 "accommodatesNumber": "2",
13 "maximumNumberOfNights": "360"
14}
15{
16 "lastScrapedDate": "2019-03-07",
17 "propertyName": "Sydney Hyde Park City Apartment (checkin from 6am)",
18 "propertyType": "Apartment",
19 "accommodatesNumber": "2",
20 "maximumNumberOfNights": "30"
21}
22{
23 "lastScrapedDate": "2019-03-07",
24 "propertyName": "Private Room (2) in Guest House at Coogee Beach",
25 "propertyType": "House",
26 "accommodatesNumber": "2",
27 "maximumNumberOfNights": "365"
28}
29{
30 "lastScrapedDate": "2019-03-06",
31 "propertyName": "~Ao Lele~ Flying Cloud",
32 "propertyType": "Treehouse",
33 "accommodatesNumber": "2",
34 "maximumNumberOfNights": "30"
35}
1

mongodb-driver-kotlin-coroutine

4.10.0 또는 그 이상의 버전

2
3

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

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

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

  • Atlas 클러스터에 대한 연결을 설정합니다.

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

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("airbnb_mat_view")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "date-number-fields-tutorial")
20 .append(
21 "queryString",
22 Document("defaultPath", "propertyType")
23 .append(
24 "query",
25 "propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019"
26 )
27 )
28 )
29
30 // run query and print results
31 val resultsFlow = collection.aggregate<Document>(
32 listOf(
33 agg,
34 limit(5),
35 project(fields(excludeId()))
36 )
37 )
38 resultsFlow.collect { println(it) }
39 }
40 mongoClient.close()
41}

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

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.excludeId
4import com.mongodb.client.model.Projections.fields
5import com.mongodb.kotlin.client.coroutine.MongoClient
6import kotlinx.coroutines.runBlocking
7import org.bson.Document
8
9fun main() {
10 // establish connection and set namespace
11 val uri = "<connection-string>"
12 val mongoClient = MongoClient.create(uri)
13 val database = mongoClient.getDatabase("sample_airbnb")
14 val collection = database.getCollection<Document>("airbnb_mat_view")
15
16 runBlocking {
17 // define query
18 val agg = Document(
19 "\$search",
20 Document("index", "date-number-fields-tutorial")
21 .append(
22 "queryString",
23 Document("defaultPath", "propertyType")
24 .append(
25 "query",
26 "propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30"
27 )
28 )
29 )
30
31 // run query and print results
32 val resultsFlow = collection.aggregate<Document>(
33 listOf(
34 agg,
35 limit(5),
36 project(fields(excludeId()))
37 )
38 )
39 resultsFlow.collect { println(it) }
40 }
41 mongoClient.close()
42}

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

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

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

  • Atlas 클러스터에 대한 연결을 설정합니다.

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

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("airbnb_mat_view")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "date-number-fields-tutorial")
20 .append(
21 "compound",
22 Document(
23 "should", listOf(
24 Document(
25 "autocomplete",
26 Document("path", "lastScrapedDate")
27 .append("query", "2")
28 ),
29 Document(
30 "autocomplete",
31 Document("path", "maximumNumberOfNights")
32 .append("query", "1")
33 )
34 )
35 )
36 )
37 )
38
39 // run query and print results
40 val resultsFlow = collection.aggregate<Document>(
41 listOf(
42 agg,
43 limit(5),
44 project(fields(excludeId()))
45 )
46 )
47 resultsFlow.collect { println(it) }
48 }
49 mongoClient.close()
50}

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

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("airbnb_mat_view")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("index", "date-number-fields-tutorial")
20 .append(
21 "compound",
22 Document(
23 "should", listOf(
24 Document(
25 "autocomplete",
26 Document("path", "maximumNumberOfNights")
27 .append("query", "3")
28 ),
29 Document(
30 "autocomplete",
31 Document("path", "accommodatesNumber")
32 .append("query", "2")
33 )
34 )
35 )
36 )
37 )
38
39 // run query and print results
40 val resultsFlow = collection.aggregate<Document>(
41 listOf(
42 agg,
43 limit(5),
44 project(fields(excludeId()))
45 )
46 )
47 resultsFlow.collect { println(it) }
48 }
49 mongoClient.close()
50}

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

4

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

Document{{lastScrapedDate=2019-03-06, propertyName=Tropical Jungle Oasis, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-03-06, propertyName=Honolulu 1 BR/1Bath Condo - Hilton Hawaiian, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=7}}
Document{{lastScrapedDate=2019-03-06, propertyName=Beautiful Apt, Tropical Resort, Steps to the Beach, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=45}}
Document{{lastScrapedDate=2019-03-06, propertyName=Ocean View in the heart of Waikiki, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-03-06, propertyName=Aloha, Kihei Bay Surf, New Pool and BBQ, propertyType=Condominium, accommodatesNumber=4, maximumNumberOfNights=1125}}

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

Document{{lastScrapedDate=2019-03-11, propertyName=This room is perfect for responsible guests, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-06, propertyName=Queen Room at Beautiful Upscale Organic Farm, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-11, propertyName=Incredible space with amazing views, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-02-16, propertyName=Varanda Porto, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-06, propertyName=Bright, Clean, Quiet, Modern, propertyType=House, accommodatesNumber=2, maximumNumberOfNights=30}}

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

Document{{lastScrapedDate=2019-03-07, propertyName=Deluxe Loft Suite, propertyType=Apartment, accommodatesNumber=4, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-03-11, propertyName=3 chambres au coeur du Plateau, propertyType=Apartment, accommodatesNumber=6, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-02-16, propertyName=Be Happy in Porto, propertyType=Loft, accommodatesNumber=2, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-02-18, propertyName=Cozy house at Beyoğlu, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=1125}}
Document{{lastScrapedDate=2019-02-16, propertyName=Downtown Oporto Inn (room cleaning), propertyType=Hostel, accommodatesNumber=2, maximumNumberOfNights=1125}}

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

Document{{lastScrapedDate=2019-03-06, propertyName=Ocean View Waikiki Marina w/prkg, propertyType=Condominium, accommodatesNumber=2, maximumNumberOfNights=365}}
Document{{lastScrapedDate=2019-03-07, propertyName=New York City - Upper West Side Apt, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=360}}
Document{{lastScrapedDate=2019-03-06, propertyName=~Ao Lele~ Flying Cloud, propertyType=Treehouse, accommodatesNumber=2, maximumNumberOfNights=30}}
Document{{lastScrapedDate=2019-03-06, propertyName=Banyan Bungalow, propertyType=Bungalow, accommodatesNumber=2, maximumNumberOfNights=300}}
Document{{lastScrapedDate=2019-03-06, propertyName=Luxury 1-Bdrm in Downtown Brooklyn, propertyType=Apartment, accommodatesNumber=2, maximumNumberOfNights=30}}
1
2

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

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

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

  • MongoClient 클래스의 인스턴스를 생성하여 Atlas 클러스터에 대한 연결을 설정합니다.

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

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'queryString': {
9 'defaultPath': 'propertyType',
10 'query': 'propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019'
11 }
12 }
13 }, {
14 '$limit': 5
15 }, {
16 '$project': {
17 '_id': 0
18 }
19 }
20];
21
22MongoClient.connect(
23 "<connection-string>",
24 { useNewUrlParser: true, useUnifiedTopology: true },
25 async function (connectErr, client) {
26 assert.equal(null, connectErr);
27 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
28 let cursor = await coll.aggregate(agg);
29 await cursor.forEach((doc) => console.log(doc));
30 client.close();
31 }
32);

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

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'queryString': {
9 'defaultPath': 'propertyType',
10 'query': 'propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30'
11 }
12 }
13 }, {
14 '$limit': 5
15 }, {
16 '$project': {
17 '_id': 0
18 }
19 }
20];
21
22MongoClient.connect(
23 "<connection-string>",
24 { useNewUrlParser: true, useUnifiedTopology: true },
25 async function (connectErr, client) {
26 assert.equal(null, connectErr);
27 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
28 let cursor = await coll.aggregate(agg);
29 await cursor.forEach((doc) => console.log(doc));
30 client.close();
31 }
32);

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

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

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

  • MongoClient 클래스의 인스턴스를 생성하여 Atlas 클러스터에 대한 연결을 설정합니다.

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

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'compound': {
9 'should': [
10 {
11 'autocomplete': {
12 'path': 'lastScrapedDate',
13 'query': '2'
14 }
15 }, {
16 'autocomplete': {
17 'path': 'maximumNumberOfNights',
18 'query': '1'
19 }
20 }
21 ]
22 }
23 }
24 }, {
25 '$limit': 5
26 }, {
27 '$project': {
28 '_id': 0
29 }
30 }
31];
32
33MongoClient.connect(
34 "<connection-string>",
35 { useNewUrlParser: true, useUnifiedTopology: true },
36 async function (connectErr, client) {
37 assert.equal(null, connectErr);
38 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
39 let cursor = await coll.aggregate(agg);
40 await cursor.forEach((doc) => console.log(doc));
41 client.close();
42 }
43);

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

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

1const MongoClient = require("mongodb").MongoClient;
2const assert = require("assert");
3
4const agg = [
5 {
6 '$search': {
7 'index': 'date-number-fields-tutorial',
8 'compound': {
9 'should': [
10 {
11 'autocomplete': {
12 'path': 'maximumNumberOfNights',
13 'query': '3'
14 }
15 }, {
16 'autocomplete': {
17 'path': 'accommodatesNumber',
18 'query': '2'
19 }
20 }
21 ]
22 }
23 }
24 }, {
25 '$limit': 5
26 }, {
27 '$project': {
28 '_id': 0
29 }
30 }
31];
32
33MongoClient.connect(
34 "<connection-string>",
35 { useNewUrlParser: true, useUnifiedTopology: true },
36 async function (connectErr, client) {
37 assert.equal(null, connectErr);
38 const coll = client.db("sample_airbnb").collection("airbnb_mat_view");
39 let cursor = await coll.aggregate(agg);
40 await cursor.forEach((doc) => console.log(doc));
41 client.close();
42 }
43);

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

3
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-03-06',
3 propertyName: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
4 propertyType: 'Condominium',
5 accommodatesNumber: '4',
6 maximumNumberOfNights: '1125'
7 }
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Makaha Valley Paradise with OceanView',
11 propertyType: 'Condominium',
12 accommodatesNumber: '4',
13 maximumNumberOfNights: '180'
14 }
15 {
16 lastScrapedDate: '2019-03-06',
17 propertyName: 'March 2019 availability! Oceanview on Sugar Beach!',
18 propertyType: 'Condominium',
19 accommodatesNumber: '4',
20 maximumNumberOfNights: '1125'
21 }
22 {
23 lastScrapedDate: '2019-03-06',
24 propertyName: 'Tropical Jungle Oasis',
25 propertyType: 'Condominium',
26 accommodatesNumber: '4',
27 maximumNumberOfNights: '1125'
28 }
29 {
30 lastScrapedDate: '2019-02-11',
31 propertyName: 'Hospede-se com acesso fácil.',
32 propertyType: 'Condominium',
33 accommodatesNumber: '4',
34 maximumNumberOfNights: '1125'
35 }
36
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-02-11',
3 propertyName: '2017 , férias no Rio',
4 propertyType: 'House',
5 accommodatesNumber: '2',
6 maximumNumberOfNights: '30'
7 }
8 {
9 lastScrapedDate: '2019-03-07',
10 propertyName: 'Newly renovated home',
11 propertyType: 'House',
12 accommodatesNumber: '2',
13 maximumNumberOfNights: '30'
14 }
15 {
16 lastScrapedDate: '2019-02-18',
17 propertyName: 'Vintage House For Rent',
18 propertyType: 'House',
19 accommodatesNumber: '2',
20 maximumNumberOfNights: '30'
21 }
22 {
23 lastScrapedDate: '2019-02-18',
24 propertyName: '4floor house in Taksim,Taksimde 4katli müstakil ev',
25 propertyType: 'House',
26 accommodatesNumber: '2',
27 maximumNumberOfNights: '30'
28 }
29 {
30 lastScrapedDate: '2019-02-16',
31 propertyName: '22 Oporto Guesthouse Cordoaria',
32 propertyType: 'House',
33 accommodatesNumber: '2',
34 maximumNumberOfNights: '30'
35 }
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-02-11',
3 propertyName: 'Horto flat with small garden',
4 propertyType: 'Apartment',
5 accommodatesNumber: '4',
6 maximumNumberOfNights: '1125'
7 }
8 {
9 lastScrapedDate: '2019-03-06',
10 propertyName: 'Private Room in Bushwick',
11 propertyType: 'Apartment',
12 accommodatesNumber: '1',
13 maximumNumberOfNights: '1125'
14 }
15 {
16 lastScrapedDate: '2019-02-11',
17 propertyName: 'Apt Linda Vista Lagoa - Rio',
18 propertyType: 'Apartment',
19 accommodatesNumber: '2',
20 maximumNumberOfNights: '1125'
21 }
22 {
23 lastScrapedDate: '2019-02-18',
24 propertyName: 'Charming Flat in Downtown Moda',
25 propertyType: 'House',
26 accommodatesNumber: '6',
27 maximumNumberOfNights: '1125'
28 }
29 {
30 lastScrapedDate: '2019-02-11',
31 propertyName: "Catete's Colonial Big Hause Room B",
32 propertyType: 'House',
33 accommodatesNumber: '8',
34 maximumNumberOfNights: '1125'
35 }
node date-number-to-string-query.js
1 {
2 lastScrapedDate: '2019-03-06',
3 propertyName: 'Ocean View Waikiki Marina w/prkg',
4 propertyType: 'Condominium',
5 accommodatesNumber: '2',
6 maximumNumberOfNights: '365'
7 }
8 {
9 lastScrapedDate: '2019-03-07',
10 propertyName: 'New York City - Upper West Side Apt',
11 propertyType: 'Apartment',
12 accommodatesNumber: '2',
13 maximumNumberOfNights: '360'
14 }
15 {
16 lastScrapedDate: '2019-03-07',
17 propertyName: 'Sydney Hyde Park City Apartment (checkin from 6am)',
18 propertyType: 'Apartment',
19 accommodatesNumber: '2',
20 maximumNumberOfNights: '30'
21 }
22 {
23 lastScrapedDate: '2019-03-07',
24 propertyName: 'Private Room (2) in Guest House at Coogee Beach',
25 propertyType: 'House',
26 accommodatesNumber: '2',
27 maximumNumberOfNights: '365'
28 }
29 {
30 lastScrapedDate: '2019-03-06',
31 propertyName: '~Ao Lele~ Flying Cloud',
32 propertyType: 'Treehouse',
33 accommodatesNumber: '2',
34 maximumNumberOfNights: '30'
35 }
1
2

동적 매핑을 사용하는 인덱스를 생성하면 쿼리 문자열 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다. 정적 매핑을 사용하는 인덱스를 생성하면 자동 완성 연산자를 사용하여 airbnb_mat_view 컬렉션을 쿼리할 수 있습니다.

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

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

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

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

다음 쿼리는 부동산 유형이 Apartment 또는 Condominium이고, 2명이 거주할 수 있으며, 2019년에 등록된 부동산을 검색합니다.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'queryString': {
10 'defaultPath': 'propertyType',
11 'query': 'propertyType: (Apartment OR Condominium) AND accommodatesNumber: 4 AND lastScrapedDate: 2019'
12 }
13 }
14 }, {
15 '$limit': 5
16 }, {
17 '$project': {
18 '_id': 0
19 }
20 }
21])
22
23for i in result:
24 print(i)

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

다음 쿼리는 숙박 시설 유형이 House 이거나, 2 명을 수용하거나, 2019 에 등록되었거나, 최대 30 박을 숙박할 수 있는 숙박 시설을 검색합니다.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'queryString': {
10 'defaultPath': 'propertyType',
11 'query': 'propertyType: House OR accommodatesNumber: 2 OR lastScrapedDate: 2019 OR maximumNumberOfNights: 30'
12 }
13 }
14 }, {
15 '$limit': 5
16 }, {
17 '$project': {
18 '_id': 0
19 }
20 }
21])
22
23for i in result:
24 print(i)

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

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

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

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

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

다음 쿼리는 2부터 시작하는 날짜에 등록된 숙소를 검색하며, 1부터 시작하는 숙박일수를 허용합니다.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'compound': {
10 'should': [
11 {
12 'autocomplete': {
13 'path': 'lastScrapedDate',
14 'query': '2'
15 }
16 }, {
17 'autocomplete': {
18 'path': 'maximumNumberOfNights',
19 'query': '1'
20 }
21 }
22 ]
23 }
24 }
25 }, {
26 '$limit': 5
27 }, {
28 '$project': {
29 '_id': 0
30 }
31 }
32])
33
34for i in result:
35 print(i)

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

다음 쿼리는 3으로 시작하는 숙박 일수를 허용하고 2로 시작하는 인원을 수용할 수 있는 숙박 시설을 검색합니다.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_airbnb']['airbnb_mat_view'].aggregate([
6 {
7 '$search': {
8 'index': 'date-number-fields-tutorial',
9 'compound': {
10 'should': [
11 {
12 'autocomplete': {
13 'path': 'maximumNumberOfNights',
14 'query': '3'
15 }
16 }, {
17 'autocomplete': {
18 'path': 'accommodatesNumber',
19 'query': '2'
20 }
21 }
22 ]
23 }
24 }
25 }, {
26 '$limit': 5
27 }, {
28 '$project': {
29 '_id': 0
30 }
31 }
32])
33
34for i in result:
35 print(i)

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

3
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-03-06',
3 'propertyName': 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
4 'propertyType': 'Condominium',
5 'accommodatesNumber': '4',
6 'maximumNumberOfNights': '1125'
7}
8{
9 'lastScrapedDate': '2019-03-06',
10 'propertyName': 'Makaha Valley Paradise with OceanView',
11 'propertyType': 'Condominium',
12 'accommodatesNumber': '4',
13 'maximumNumberOfNights': '180'
14}
15{
16 'lastScrapedDate': '2019-03-06',
17 'propertyName': 'March 2019 availability! Oceanview on Sugar Beach!',
18 'propertyType': 'Condominium',
19 'accommodatesNumber': '4',
20 'maximumNumberOfNights': '1125'
21}
22{
23 'lastScrapedDate': '2019-03-06',
24 'propertyName': 'Tropical Jungle Oasis',
25 'propertyType': 'Condominium',
26 'accommodatesNumber': '4',
27 'maximumNumberOfNights': '1125'
28}
29{
30 'lastScrapedDate': '2019-02-11',
31 'propertyName': 'Hospede-se com acesso fácil.',
32 'propertyType': 'Condominium',
33 'accommodatesNumber': '4',
34 'maximumNumberOfNights': '1125'
35}
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-02-11',
3 'propertyName': '2017 , férias no Rio',
4 'propertyType': 'House',
5 'accommodatesNumber': '2',
6 'maximumNumberOfNights': '30'
7}
8{
9 'lastScrapedDate': '2019-03-07',
10 'propertyName': 'Newly renovated home',
11 'propertyType': 'House',
12 'accommodatesNumber': '2',
13 'maximumNumberOfNights': '30'
14}
15{
16 'lastScrapedDate': '2019-02-18',
17 'propertyName': 'Vintage House For Rent',
18 'propertyType': 'House',
19 'accommodatesNumber': '2',
20 'maximumNumberOfNights': '30'
21}
22{
23 'lastScrapedDate': '2019-02-18',
24 'propertyName': '4floor house in Taksim,Taksimde 4katli müstakil ev',
25 'propertyType': 'House',
26 'accommodatesNumber': '2',
27 'maximumNumberOfNights': '30'
28}
29{
30 'lastScrapedDate': '2019-02-16',
31 'propertyName': '22 Oporto Guesthouse Cordoaria',
32 'propertyType': 'House',
33 'accommodatesNumber': '2',
34 'maximumNumberOfNights': '30'
35}
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-02-11',
3 'propertyName': 'Horto flat with small garden',
4 'propertyType': 'Apartment',
5 'accommodatesNumber': '4',
6 'maximumNumberOfNights': '1125'
7}
8{
9 'lastScrapedDate': '2019-03-06',
10 'propertyName': 'Private Room in Bushwick',
11 'propertyType': 'Apartment',
12 'accommodatesNumber': '1',
13 'maximumNumberOfNights': '1125'
14}
15{
16 'lastScrapedDate': '2019-02-11',
17 'propertyName': 'Apt Linda Vista Lagoa - Rio',
18 'propertyType': 'Apartment',
19 'accommodatesNumber': '2',
20 'maximumNumberOfNights': '1125'
21}
22{
23 'lastScrapedDate': '2019-02-18',
24 'propertyName': 'Charming Flat in Downtown Moda',
25 'propertyType': 'House',
26 'accommodatesNumber': '6',
27 'maximumNumberOfNights': '1125'
28}
29{
30 'lastScrapedDate': '2019-02-11',
31 'propertyName': "Catete's Colonial Big Hause Room B",
32 'propertyType': 'House',
33 'accommodatesNumber': '8',
34 'maximumNumberOfNights': '1125'
35}
python date-number-to-string-query.py
1{
2 'lastScrapedDate': '2019-03-06',
3 'propertyName': 'Ocean View Waikiki Marina w/prkg',
4 'propertyType': 'Condominium',
5 'accommodatesNumber': '2',
6 'maximumNumberOfNights': '365'
7}
8{
9 'lastScrapedDate': '2019-03-07',
10 'propertyName': 'New York City - Upper West Side Apt',
11 'propertyType': 'Apartment',
12 'accommodatesNumber': '2',
13 'maximumNumberOfNights': '360'
14}
15{
16 'lastScrapedDate': '2019-03-07',
17 'propertyName': 'Sydney Hyde Park City Apartment (checkin from 6am)',
18 'propertyType': 'Apartment',
19 'accommodatesNumber': '2',
20 'maximumNumberOfNights': '30'
21}
22{
23 'lastScrapedDate': '2019-03-07',
24 'propertyName': 'Private Room (2) in Guest House at Coogee Beach',
25 'propertyType': 'House',
26 'accommodatesNumber': '2',
27 'maximumNumberOfNights': '365'
28}
29{
30 'lastScrapedDate': '2019-03-06',
31 'propertyName': '~Ao Lele~ Flying Cloud',
32 'propertyType': 'Treehouse',
33 'accommodatesNumber': '2',
34 'maximumNumberOfNights': '30'
35}