Docs Menu
Docs Home
/
Atlas
/ / / /

geoWithin 연산자

geoWithin

geoWithin 연산자는 주어진 지오메트리 내의 지리적 점에 대한 쿼리를 지원합니다. 인덱스 정의에서 indexShapes 값이 true인 경우에도 점만 반환됩니다.

다음 항목 내의 점을 쿼리할 수 있습니다.

  • 경계 박스

  • 다각형

검색할 좌표를 지정할 때는 경도를 먼저 지정한 다음 위도를 지정해야 합니다. 경도 값 범위는 -180 ~ 180 사이이며 둘 다 포함합니다. 위도 값 범위는 -90 ~ 90 이며 둘 다 포함합니다. 좌표 값은 정수 또는 이중 값일 수 있습니다.

참고

Atlas Search에서는 다음을 지원하지 않습니다.

  • 기본값이 좌표 기준계(CRS)

  • 평면형 XY 좌표계(2차원)

  • 좌표 쌍 점 표기법(즉, pointFieldName: [12, 34])

geoWithin 의 구문은 다음과 같습니다:

{
"$search": {
"index": <index name>, // optional, defaults to "default"
"geoWithin": {
"path": "<field-to-search>",
"box | circle | geometry": <object>,
"score": <score-options>
}
}
}

geoWithin 는 다음 용어를 사용하여 쿼리를 구성합니다:

필드
유형
설명
필요성

box

객체

검색할 상자의 왼쪽 아래와 오른쪽 위 GeoJSON 포인트를 지정하는 객체입니다. 객체는 다음 필드를 사용합니다.

  • bottomLeft - 왼쪽 하단 GeoJSON 포인트.

  • topRight - 오른쪽 상단 GeoJSON 점.

GeoJSON 객체 내에서 GeoJSON 데이터를 지정하는 방법을 알아보려면 GeoJSON 객체를 참조하세요.

box, circle 또는 geometry 중 하나가 필요합니다.

조건부

circle

객체

Atlas Search의 중심점과 반경을 미터 단위로 지정하는 객체입니다. 객체에는 다음과 같은 GeoJSON 필드가 포함되어 있습니다.

  • center - GeoJSON 포인트로 지정된 원의 중심입니다.

  • radius - 숫자인 반경은 미터 단위로 지정됩니다. 값은 0 이상이어야 합니다.

GeoJSON 객체 내에서 GeoJSON 데이터를 지정하는 방법을 알아보려면 GeoJSON 객체를 참조하세요.

circle, box 또는 geometry 중 하나가 필요합니다.

조건부

geometry

GeoJSON 객체

Atlas Search 내에서 다중 GeoJSON 다각형 또는 다각형 을 지정하는 객체입니다. 다각형은 마지막 위치가 첫 번째 위치와 동일한 닫힌 루프로 지정되어야 합니다.

지리 공간적 결과를 계산할 때 Atlas Search geoShapegeoWithin 연산자와 MongoDB $geoIntersects 연산자 서로 다른 도형을 사용합니다. 이 차이는 Atlas Search 와 MongoDB 다각형 가장자리를 그리는 방식에서 확인할 수 있습니다.

Atlas Search는 데카르트 거리 를 기반으로 다각형을 그립니다. 은 좌표 참조 시스템에서 두 점을 잇는 가장 짧은 선입니다.

MongoDB 측지 유형용 타사 라이브러리를 기반으로 하는 2dsphere 인덱스를 기반으로 하는 측지 모드 또는 2d 인덱스의 플랫 모드 사용하여 다각형을 그립니다. 자세한 학습 GeoJSON 객체를 참조하세요.

Atlas Search와 MongoDB는 다각형과 관련된 지리 공간적 쿼리에 대해 서로 다른 결과를 반환할 수 있습니다.

GeoJSON 객체 내에서 GeoJSON 데이터를 지정하는 방법을 알아보려면 GeoJSON 객체를 참조하세요.

geometry, box 또는 circle 중 하나가 필요합니다.

조건부

path

문자열 또는 문자열 배열

검색할 인덱싱된 geo 유형 필드.

score

객체

일치하는 검색 결과에 할당할 점수입니다. 기본적으로 결과의 점수1 입니다. 다음 옵션을 사용하여 점수를 수정할 수 있습니다.

  • boost결과 점수에 주어진 숫자를 곱합니다.

  • constant결과 점수를 주어진 숫자로 바꿉니다.

  • function결과 점수를 주어진 표현식으로 대체합니다.

쿼리에서 score 사용에 대한 자세한 내용은 결과에서 문서 채점하기를 참조하십시오.

no

다음 예제에서는 sample_airbnb 데이터베이스의 listingsAndReviews 컬렉션을 사용합니다. 클러스터에 샘플 데이터 세트 가 있는 경우 지리적 유형에 대한 사용자 지정 Atlas Search 인덱스를 만들고 클러스터에서 예제 쿼리를 실행할 수 있습니다.

listingsAndReviews collection의 address.location 필드를 인덱싱하려면 다음 샘플 인덱스 정의를 사용합니다.

1{
2 "mappings": {
3 "fields": {
4 "address": {
5 "fields": {
6 "location": {
7 "type": "geo"
8 }
9 },
10 "type": "document"
11 },
12 "property_type": {
13 "type": "token"
14 }
15 }
16 }
17}

다음 쿼리는 geoWithin 연산자와 box 필드를 사용하여 오스트레일리아의 경계 상자 내 속성을 검색합니다.

쿼리에는 다음이 포함됩니다.

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

  • nameaddress를 제외한 모든 필드를 제외하려면 $project 단계를 수행합니다.

참고

Atlas Search 검색 쿼리에 default 이라는 인덱스를 지정할 필요가 없습니다. 인덱스에 다른 이름이 있는 경우 index 필드를 지정해야 합니다.

다음 쿼리는 지정된 검색 기준과 일치하는 문서를 반환합니다.

1db.listingsAndReviews.aggregate([
2 {
3 "$search": {
4 "geoWithin": {
5 "path": "address.location",
6 "box": {
7 "bottomLeft": {
8 "type": "Point",
9 "coordinates": [112.467, -55.050]
10 },
11 "topRight": {
12 "type": "Point",
13 "coordinates": [168.000, -9.133]
14 }
15 }
16 }
17 }
18 },
19 {
20 $limit: 3
21 },
22 {
23 $project: {
24 "_id": 0,
25 "name": 1,
26 "address": 1
27 }
28 }
29])
{
"name" : "Surry Hills Studio - Your Perfect Base in Sydney",
"address" : {
"street" : "Surry Hills, NSW, Australia",
"suburb" : "Darlinghurst",
"government_area" : "Sydney",
"market" : "Sydney",
"country" : "Australia",
"country_code" : "AU",
"location" : {
"type" : "Point",
"coordinates" : [ 151.21554, -33.88029 ],
"is_location_exact" : true
}
}
}
{
"name" : "Sydney Hyde Park City Apartment (checkin from 6am)",
"address" : {
"street" : "Darlinghurst, NSW, Australia",
"suburb" : "Darlinghurst",
"government_area" : "Sydney",
"market" : "Sydney",
"country" : "Australia",
"country_code" : "AU",
"location" : {
"type" : "Point",
"coordinates" : [ 151.21346, -33.87603 ],
"is_location_exact" : false
}
}
}
{
"name" : "THE Place to See Sydney's FIREWORKS",
"address" : {
"street" : "Rozelle, NSW, Australia",
"suburb" : "Lilyfield/Rozelle",
"government_area" : "Leichhardt",
"market" : "Sydney",
"country" : "Australia",
"country_code" : "AU",
"location" : {
"type" : "Point",
"coordinates" : [ 151.17956, -33.86296 ],
"is_location_exact" : true
}
}
}

다음 쿼리는 지정된 검색 조건에 따라 아파트, 주택 등의 부동산 유형 수를 반환합니다.

1db.listingsAndReviews.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "geoWithin": {
7 "path": "address.location",
8 "box": {
9 "bottomLeft": {
10 "type": "Point",
11 "coordinates": [112.467, -55.050]
12 },
13 "topRight": {
14 "type": "Point",
15 "coordinates": [168.000, -9.133]
16 }
17 }
18 }
19 },
20 "facets": {
21 "propertyTypeFacet": {
22 "type": "string",
23 "path": "property_type"
24 }
25 }
26 }
27 }
28 }
29])
[
{
count: { lowerBound: Long('610') },
facet: {
propertyTypeFacet: {
buckets: [
{ _id: 'Apartment', count: Long('334') },
{ _id: 'House', count: Long('168') },
{ _id: 'Townhouse', count: Long('29') },
{ _id: 'Guest suite', count: Long('20') },
{ _id: 'Condominium', count: Long('11') },
{ _id: 'Cabin', count: Long('8') },
{ _id: 'Serviced apartment', count: Long('7') },
{ _id: 'Villa', count: Long('7') },
{ _id: 'Bungalow', count: Long('5') },
{ _id: 'Guesthouse', count: Long('5') }
]
}
}
}
]

다음 쿼리는 geoWithin 연산자와 circle 필드를 사용하여 캐나다의 지정된 좌표에서 반경 1마일 이내에 있는 속성을 검색합니다.

쿼리에는 다음이 포함됩니다.

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

  • nameaddress를 제외한 모든 필드를 제외하려면 $project 단계를 수행합니다.

참고

Atlas Search 검색 쿼리에 default 이라는 인덱스를 지정할 필요가 없습니다. 인덱스에 다른 이름이 있는 경우 index 필드를 지정해야 합니다.

1db.listingsAndReviews.aggregate([
2 {
3 "$search": {
4 "geoWithin": {
5 "circle": {
6 "center": {
7 "type": "Point",
8 "coordinates": [-73.54, 45.54]
9 },
10 "radius": 1600
11 },
12 "path": "address.location"
13 }
14 }
15 },
16 {
17 $limit: 3
18 },
19 {
20 $project: {
21 "_id": 0,
22 "name": 1,
23 "address": 1
24 }
25 }
26])
{
"name" : "Ligne verte - à 15 min de métro du centre ville.",
"address" : {
"street" : "Montréal, Québec, Canada",
"suburb" : "Hochelaga-Maisonneuve",
"government_area" : "Mercier-Hochelaga-Maisonneuve",
"market" : "Montreal",
"country" : "Canada",
"country_code" : "CA",
"location" : {
"type" : "Point",
"coordinates" : [ -73.54949, 45.54548 ],
"is_location_exact" : false
}
}
}
{
"name" : "Belle chambre à côté Metro Papineau",
"address" : {
"street" : "Montréal, QC, Canada",
"suburb" : "Gay Village",
"government_area" : "Ville-Marie",
"market" : "Montreal",
"country" : "Canada",
"country_code" : "CA",
"location" : {
"type" : "Point",
"coordinates" : [ -73.54985, 45.52797 ],
"is_location_exact" : false
}
}
}
{
"name" : "L'IDÉAL, ( à 2 min du métro Pie-IX ).",
"address" : {
"street" : "Montréal, Québec, Canada",
"suburb" : "Mercier-Hochelaga-Maisonneuve",
"government_area" : "Mercier-Hochelaga-Maisonneuve",
"market" : "Montreal",
"country" : "Canada",
"country_code" : "CA",
"location" : {
"type" : "Point",
"coordinates" : [ -73.55208, 45.55157 ],
"is_location_exact" : true
}
}
}

다음 예시에서는 geometry 필드와 함께 geoWithin 연산자를 사용하여 하와이의 속성을 검색합니다. type 필드는 해당 영역이 GeoJSON 다각형인지 다중 다각형인지를 지정합니다.

쿼리에는 다음이 포함됩니다.

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

  • nameaddress를 제외한 모든 필드를 제외하려면 $project 단계를 수행합니다.

참고

Atlas Search 검색 쿼리에 default 이라는 인덱스를 지정할 필요가 없습니다. 인덱스에 다른 이름이 있는 경우 index 필드를 지정해야 합니다.


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


다음 Atlas Search 쿼리:

  • 복합 $search 단계를 사용하여 다음을 수행합니다.

    • 결과 mustcoordinates 세트에 의해 정의된 Polygon 내에 포함되도록 지정합니다.

    • condominium 유형의 속성에 대한 결과에 우선 순위를 부여합니다.

  • $project 단계를 사용하여 다음을 수행합니다.

    • name, addressproperty_type 를 제외한 모든 필드를 제외합니다.

    • 반환된 각 문서에 관련성 score 을 추가합니다.

[
{
"$search": {
"index": "<INDEX-NAME>",
"compound": {
"must": [{
"geoWithin": {
"geometry": {
"type": "Polygon",
"coordinates": [[[ -161.323242, 22.512557 ],
[ -152.446289, 22.065278 ],
[ -156.09375, 17.811456 ],
[ -161.323242, 22.512557 ]]]
},
"path": "address.location"
}
}],
"should": [{
"text": {
"path": "property_type",
"query": "Condominium"
}
}]
}
}
}
]
1SCORE: 2.238388776779175 _id: "1001265"
2listing_url: "https://www.airbnb.com/rooms/1001265"
3name: "Ocean View Waikiki Marina w/prkg"
4summary: "A short distance from Honolulu's billion dollar mall,
5and the same dis…"
6...
7property_type: "Condominium"
8...
9address: Object
10 street: "Honolulu, HI, United States"
11 suburb: "Oʻahu"
12 government_area: "Primary Urban Center"
13 market: "Oahu"
14 country: "United States"
15 country_code: "US"
16 location: Object
17 type: "Point"
18 coordinates: Array
19 0: -157.83919
20 1: 21.28634
21 is_location_exact: true
22...
23
24SCORE: 2.238388776779175 _id: "10227000"
25listing_url: "https://www.airbnb.com/rooms/10227000"
26name: "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!"
27summary: "THIS IS A VERY SPACIOUS 1 BEDROOM FULL CONDO (SLEEPS 4) AT THE BEAUTIF…"
28...
29property_type: "Condominium"
30...
31address: Object
32 street: "Lahaina, HI, United States"
33 suburb: "Maui"
34 government_area: "Lahaina"
35 market: "Maui"
36 country: "United States"
37 country_code: "US"
38 location: Object
39 type: "Point"
40 coordinates: Array
41 0: -156.68012
42 1: 20.96996
43 is_location_exact: true
44...
45
46SCORE: 2.238388776779175 _id: "10266175"
47listing_url: "https://www.airbnb.com/rooms/10266175"
48name: "Makaha Valley Paradise with OceanView"
49summary: "A beautiful and comfortable 1 Bedroom Air Conditioned Condo in Makaha …"
50...
51property_type: "Condominium"
52...
53address: Object
54 street: "Waianae, HI, United States"
55 suburb: "Leeward Side"
56 government_area: "Waianae"
57 market: "Oahu"
58 country: "United States"
59 country_code: "US"
60 location: Object
61 type: "Point"
62 coordinates: Array
63 0: -158.20291
64 1: 21.4818
65 is_location_exact: true
66...
67
68SCORE: 2.238388776779175 _id: "1042446"
69listing_url: "https://www.airbnb.com/rooms/1042446"
70name: "March 2019 availability! Oceanview on Sugar Beach!"
71summary: ""
72...
73property_type: "Condominium"
74...
75address: Object
76 street: "Kihei, HI, United States"
77 suburb: "Maui"
78 government_area: "Kihei-Makena"
79 market: "Maui"
80 country: "United States"
81 country_code: "US"
82 location: Object
83 type: "Point"
84 coordinates: Array
85 0: -156.46881
86 1: 20.78621
87 is_location_exact: true
88...
89
90SCORE: 2.238388776779175 _id: "10527243"
91listing_url: "https://www.airbnb.com/rooms/10527243"
92name: "Tropical Jungle Oasis"
93summary: "2 bedrooms, one with a queen sized bed, one with 2 single beds. 1 and …"
94...
95property_type: "Condominium"
96...
97address: Object
98 street: "Hilo, HI, United States"
99 suburb: "Island of Hawaiʻi"
100 government_area: "South Hilo"
101 market: "The Big Island"
102 country: "United States"
103 country_code: "US"
104 location: Object
105 type: "Point"
106 coordinates: Array
107 0: -155.09259
108 1: 19.73108
109 is_location_exact: true
110...
111
112SCORE: 2.238388776779175 _id: "1104768"
113listing_url: "https://www.airbnb.com/rooms/1104768"
114name: "2 Bdrm/2 Bath Family Suite Ocean View"
115summary: "This breathtaking 180 degree view of Waikiki is one of a kind. You wil…"
116...
117property_type: "Condominium"
118...
119address: Object
120 street: "Honolulu, HI, United States"
121 suburb: "Waikiki"
122 government_area: "Primary Urban Center"
123 market: "Oahu"
124 country: "United States"
125 country_code: "US"
126 location: Object
127 type: "Point"
128 coordinates: Array
129 0: -157.82696
130 1: 21.27971
131 is_location_exact: true
132...
133
134SCORE: 2.238388776779175 _id: "11207193"
135listing_url: "https://www.airbnb.com/rooms/11207193"
136name: "302 Kanai A Nalu Ocean front/view"
137summary: "Welcome to Kana'i A Nalu a quiet resort that sits on the ocean away fr…"
138...
139property_type: "Condominium"
140...
141address: Object
142 street: "Wailuku, HI, United States"
143 suburb: "Maui"
144 government_area: "Kihei-Makena"
145 market: "Maui"
146 country: "United States"
147 country_code: "US"
148 location: Object
149 type: "Point"
150 coordinates: Array
151 0: -156.5039
152 1: 20.79664
153 is_location_exact: true
154...
155
156SCORE: 2.238388776779175 _id: "11319047"
157listing_url: "https://www.airbnb.com/rooms/11319047"
158name: "Sugar Beach Resort 1BR Ground Floor Condo !"
159summary: "The Sugar Beach Resort enjoys a beachfront setting fit for a postcard."
160...
161property_type: "Condominium"
162...
163address: Object
164 street: "Kihei, HI, United States"
165 suburb: "Maui"
166 government_area: "Kihei-Makena"
167 market: "Maui"
168 country: "United States"
169 country_code: "US"
170 location: Object
171 type: "Point"
172 coordinates: Array
173 0: -156.46697
174 1: 20.78484
175 is_location_exact: true
176...
177
178SCORE: 2.238388776779175 _id: "11695887"
179listing_url: "https://www.airbnb.com/rooms/11695887"
180name: "2 BR Oceanview - Great Location!"
181summary: "Location, location, location... This is a great 2 bed, 2 bath condo is…"
182...
183property_type: "Condominium"
184...
185address: Object
186 street: "Kihei, HI, United States"
187 suburb: "Kihei/Wailea"
188 government_area: "Kihei-Makena"
189 market: "Maui"
190 country: "United States"
191 country_code: "US"
192 location: Object
193 type: "Point"
194 coordinates: Array
195 0: -156.44917
196 1: 20.73013
197 is_location_exact: true
198...
199
200SCORE: 2.238388776779175 _id: "11817249"
201listing_url: "https://www.airbnb.com/rooms/11817249"
202name: "PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC"
203summary: "Book with confidence this stunning 2 bedroom, 2 bathroom condo at the …"
204...
205property_type: "Condominium"
206...
207address: Object
208 street: "Kihei, HI, United States"
209 suburb: "Maui"
210 government_area: "Kihei-Makena"
211 market: "Maui"
212 country: "United States"
213 country_code: "US"
214 location: Object
215 type: "Point"
216 coordinates: Array
217 0: -156.4409
218 1: 20.69735
219 is_location_exact: true
220...
db.listingsAndReviews.aggregate([
{
"$search": {
"index": "<INDEX-NAME>",
"compound": {
"must": [{
"geoWithin": {
"geometry": {
"type": "Polygon",
"coordinates": [[[ -161.323242, 22.512557 ],
[ -152.446289, 22.065278 ],
[ -156.09375, 17.811456 ],
[ -161.323242, 22.512557 ]]]
},
"path": "address.location"
}
}],
"should": [{
"text": {
"path": "property_type",
"query": "Condominium"
}
}]
}
}
},
{
"$limit": 10
},
{
$project: {
"_id": 0,
"name": 1,
"address": 1,
"property_type": 1,
score: { $meta: "searchScore" }
}
}
])
{
name: 'Ocean View Waikiki Marina w/prkg',
property_type: 'Condominium',
address: {
street: 'Honolulu, HI, United States',
suburb: 'Oʻahu',
government_area: 'Primary Urban Center',
market: 'Oahu',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -157.83919, 21.28634 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
property_type: 'Condominium',
address: {
street: 'Lahaina, HI, United States',
suburb: 'Maui',
government_area: 'Lahaina',
market: 'Maui',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -156.68012, 20.96996 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: 'Makaha Valley Paradise with OceanView',
property_type: 'Condominium',
address: {
street: 'Waianae, HI, United States',
suburb: 'Leeward Side',
government_area: 'Waianae',
market: 'Oahu',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -158.20291, 21.4818 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: 'March 2019 availability! Oceanview on Sugar Beach!',
property_type: 'Condominium',
address: {
street: 'Kihei, HI, United States',
suburb: 'Maui',
government_area: 'Kihei-Makena',
market: 'Maui',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -156.46881, 20.78621 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: 'Tropical Jungle Oasis',
property_type: 'Condominium',
address: {
street: 'Hilo, HI, United States',
suburb: 'Island of Hawaiʻi',
government_area: 'South Hilo',
market: 'The Big Island',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -155.09259, 19.73108 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: '2 Bdrm/2 Bath Family Suite Ocean View',
property_type: 'Condominium',
address: {
street: 'Honolulu, HI, United States',
suburb: 'Waikiki',
government_area: 'Primary Urban Center',
market: 'Oahu',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -157.82696, 21.27971 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: '302 Kanai A Nalu Ocean front/view',
property_type: 'Condominium',
address: {
street: 'Wailuku, HI, United States',
suburb: 'Maui',
government_area: 'Kihei-Makena',
market: 'Maui',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -156.5039, 20.79664 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: 'Sugar Beach Resort 1BR Ground Floor Condo !',
property_type: 'Condominium',
address: {
street: 'Kihei, HI, United States',
suburb: 'Maui',
government_area: 'Kihei-Makena',
market: 'Maui',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -156.46697, 20.78484 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: '2 BR Oceanview - Great Location!',
property_type: 'Condominium',
address: {
street: 'Kihei, HI, United States',
suburb: 'Kihei/Wailea',
government_area: 'Kihei-Makena',
market: 'Maui',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -156.44917, 20.73013 ],
is_location_exact: true
}
},
score: 2.238388776779175
},
{
name: 'PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC',
property_type: 'Condominium',
address: {
street: 'Kihei, HI, United States',
suburb: 'Maui',
government_area: 'Kihei-Makena',
market: 'Maui',
country: 'United States',
country_code: 'US',
location: {
type: 'Point',
coordinates: [ -156.4409, 20.69735 ],
is_location_exact: true
}
},
score: 2.238388776779175
}
]

MongoDB Compass에서 다음 쿼리를 실행하는 방법을 알아보려면 쿼리 정의를 참조하세요.

1using MongoDB.Bson;
2using MongoDB.Bson.IO;
3using MongoDB.Bson.Serialization;
4using MongoDB.Bson.Serialization.Attributes;
5using MongoDB.Bson.Serialization.Conventions;
6using MongoDB.Driver;
7using MongoDB.Driver.GeoJsonObjectModel;
8using MongoDB.Driver.Search;
9using System;
10
11public class GeoQuery
12{
13 private const string MongoConnectionString = "<connection-string>";
14
15 public static void Main(string[] args)
16 {
17 // allow automapping of the camelCase database fields to our AirbnbDocument
18 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
19 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
20
21 // connect to your Atlas cluster
22 var mongoClient = new MongoClient(MongoConnectionString);
23 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
24 var airbnbCollection = airbnbDatabase.GetCollection<AirbnbDocument>("listingsAndReviews");
25
26 // declare data for the compound query
27 string property_type = "Condominium";
28 var coordinates = new GeoJson2DCoordinates[]
29 {
30 new(-161.323242, 22.512557),
31 new(-152.446289, 22.065278),
32 new(-156.09375, 17.811456),
33 new(-161.323242, 22.512557)
34 };
35 var polygon = GeoJson.Polygon(coordinates);
36
37 // define and run pipeline
38 var results = airbnbCollection.Aggregate()
39 .Search(Builders<AirbnbDocument>.Search.Compound()
40 .Must(Builders<AirbnbDocument>.Search.GeoWithin(airbnb => airbnb.Address.Location, polygon))
41 .Should((Builders<AirbnbDocument>.Search.Text(airbnb => airbnb.PropertyType, property_type))),
42 indexName: "<INDEX-NAME>")
43 .Limit (10)
44 .Project<AirbnbDocument>(Builders<AirbnbDocument>.Projection
45 .Include(airbnb => airbnb.PropertyType)
46 .Include(airbnb => airbnb.Address.Location)
47 .Include(airbnb => airbnb.Name)
48 .Exclude(airbnb => airbnb.Id)
49 .MetaSearchScore(airbnb => airbnb.Score))
50 .ToList();
51
52 // print results
53 foreach (var x in results) {
54 Console.WriteLine(x.ToJson());
55 }
56 }
57}
58[BsonIgnoreExtraElements]
59public class AirbnbDocument
60{
61 [BsonIgnoreIfDefault]
62 public ObjectId Id { get; set; }
63 public String Name { get; set; }
64 [BsonElement("property_type")]
65 public string PropertyType { get; set; }
66 public Address Address { get; set; }
67 public double Score { get; set; }
68}
69[BsonIgnoreExtraElements]
70public class Address
71{
72 public GeoJsonPoint<GeoJson2DCoordinates> Location { get; set; }
73}
{
"name" : "Ocean View Waikiki Marina w/prkg",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-157.83919, 21.286339999999999],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-156.68011999999999, 20.96996],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "Makaha Valley Paradise with OceanView",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-158.20291, 21.4818],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "March 2019 availability! Oceanview on Sugar Beach!",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-156.46880999999999, 20.786210000000001],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "Tropical Jungle Oasis",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-155.09259, 19.731079999999999],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "2 Bdrm/2 Bath Family Suite Ocean View",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-157.82696000000001, 21.279710000000001],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "302 Kanai A Nalu Ocean front/view",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-156.50389999999999, 20.79664],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "Sugar Beach Resort 1BR Ground Floor Condo !",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-156.46697, 20.784839999999999],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "2 BR Oceanview - Great Location!",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-156.44917000000001, 20.730129999999999],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
{
"name" : "PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC",
"property_type" : "Condominium",
"address" : {
"location" : {
"type" : "Point",
"coordinates" : [-156.4409, 20.69735],
"is_location_exact" : true
}
},
"score" : 2.2383887767791748
}
1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/v2/bson"
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("sample_airbnb").Collection("listingsAndReviews")
22
23 // define polygon
24 polygon := [][][]float64{{
25 {-161.323242, 22.512557},
26 {-152.446289, 22.065278},
27 {-156.09375, 17.811456},
28 {-161.323242, 22.512557},
29 }}
30
31 // define pipeline
32 searchStage := bson.D{{"$search", bson.M{
33 "index": "<INDEX-NAME>",
34 "compound": bson.M{
35 "must": bson.M{
36 "geoWithin": bson.M{
37 "geometry": bson.M{
38 "type": "Polygon",
39 "coordinates": polygon,
40 },
41 "path": "address.location",
42 },
43 },
44 "should": bson.M{
45 "text": bson.M{
46 "path": "property_type",
47 "query": "Condominium",
48 }},
49 },
50 },
51 }}
52 limitStage := bson.D{{"$limit", 10}}
53 projectStage := bson.D{{"$project", bson.D{{"name", 1}, {"address", 1}, {"property_type", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
54
55 // run pipeline
56 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
57 if err != nil {
58 panic(err)
59 }
60
61 // print results
62 var results []bson.D
63 if err = cursor.All(context.TODO(), &results); err != nil {
64 panic(err)
65 }
66 for _, result := range results {
67 fmt.Println(result)
68 }
69}
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_airbnb").Collection("listingsAndReviews")
// define polygon
polygon := [][][]float64{{
{-161.323242, 22.512557},
{-152.446289, 22.065278},
{-156.09375, 17.811456},
{-161.323242, 22.512557},
}}
// define pipeline
searchStage := bson.D{{"$search", bson.M{
"index": "<INDEX-NAME>",
"compound": bson.M{
"must": bson.M{
"geoWithin": bson.M{
"geometry": bson.M{
"type": "Polygon",
"coordinates": polygon,
},
"path": "address.location",
},
},
"should": bson.M{
"text": bson.M{
"path": "property_type",
"query": "Condominium",
}},
},
},
}}
limitStage := bson.D{{"$limit", 10}}
projectStage := bson.D{{"$project", bson.D{{"name", 1}, {"address", 1}, {"property_type", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}
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.computed;
6import static com.mongodb.client.model.Projections.excludeId;
7import static com.mongodb.client.model.Projections.fields;
8import static com.mongodb.client.model.Projections.include;
9import com.mongodb.client.MongoClient;
10import com.mongodb.client.MongoClients;
11import com.mongodb.client.MongoCollection;
12import com.mongodb.client.MongoDatabase;
13import org.bson.Document;
14
15public class GeoQuery {
16 public static void main( String[] args ) {
17 Document agg = new Document( "$search",
18 new Document( "index", "<INDEX-NAME>")
19 .append("compound",
20 new Document("must", Arrays.asList(new Document("geoWithin",
21 new Document("geometry",
22 new Document("type", "Polygon")
23 .append("coordinates", Arrays.asList(Arrays.asList(Arrays.asList(-161.323242d, 22.512557d), Arrays.asList(-152.446289d, 22.065278d), Arrays.asList(-156.09375d, 17.811456d), Arrays.asList(-161.323242d, 22.512557d)))))
24 .append("path", "address.location"))))
25 .append("should", Arrays.asList(new Document("text",
26 new Document("path", "property_type")
27 .append("query", "Condominium"))))));
28
29 String uri = "<connection-string>";
30
31 try (MongoClient mongoClient = MongoClients.create(uri)) {
32 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
33 MongoCollection<Document> collection = database.getCollection("listingsAndReviews");
34
35 collection.aggregate(Arrays.asList(agg,
36 limit(10),
37 project(fields(excludeId(), include("name", "address", "property_type"), computed("score", new Document("$meta", "searchScore"))))))
38 .forEach(doc -> System.out.println(doc.toJson() + "\n"));
39 }
40 }
41}

다음 코드 예제에서는:

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

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

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

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 // connect to your Atlas cluster
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12
13 // set namespace
14 val database = mongoClient.getDatabase("sample_airbnb")
15 val collection = database.getCollection<Document>("listingsAndReviews")
16
17 runBlocking {
18 // define pipeline
19 val agg = Document(
20 "\$search",
21 Document("index", "<INDEX-NAME>")
22 .append(
23 "compound",
24 Document(
25 "must", listOf(
26 Document(
27 "geoWithin",
28 Document(
29 "geometry",
30 Document("type", "Polygon")
31 .append(
32 "coordinates",
33 listOf(
34 listOf(
35 listOf(-161.323242, 22.512557),
36 listOf(-152.446289, 22.065278),
37 listOf(-156.09375, 17.811456),
38 listOf(-161.323242, 22.512557)
39 )
40 )
41 )
42 )
43 .append("path", "address.location")
44 )
45 )
46 )
47 .append(
48 "should", listOf(
49 Document(
50 "text",
51 Document("path", "property_type")
52 .append("query", "Condominium")
53 )
54 )
55 )
56 )
57 )
58
59 // run pipeline and print results
60 val resultsFlow = collection.aggregate<Document>(
61 listOf(
62 agg,
63 limit(10),
64 project(fields(
65 excludeId(),
66 include("name", "address", "property_type"),
67 computed("score", Document("\$meta", "searchScore"))
68 ))
69 )
70 )
71 resultsFlow.collect { println(it) }
72 }
73 mongoClient.close()
74}
Document{{name=Ocean View Waikiki Marina w/prkg, property_type=Condominium, address=Document{{street=Honolulu, HI, United States, suburb=Oʻahu, government_area=Primary Urban Center, market=Oahu, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-157.83919, 21.28634], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!, property_type=Condominium, address=Document{{street=Lahaina, HI, United States, suburb=Maui, government_area=Lahaina, market=Maui, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-156.68012, 20.96996], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=Makaha Valley Paradise with OceanView, property_type=Condominium, address=Document{{street=Waianae, HI, United States, suburb=Leeward Side, government_area=Waianae, market=Oahu, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-158.20291, 21.4818], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=March 2019 availability! Oceanview on Sugar Beach!, property_type=Condominium, address=Document{{street=Kihei, HI, United States, suburb=Maui, government_area=Kihei-Makena, market=Maui, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-156.46881, 20.78621], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=Tropical Jungle Oasis, property_type=Condominium, address=Document{{street=Hilo, HI, United States, suburb=Island of Hawaiʻi, government_area=South Hilo, market=The Big Island, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-155.09259, 19.73108], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=2 Bdrm/2 Bath Family Suite Ocean View, property_type=Condominium, address=Document{{street=Honolulu, HI, United States, suburb=Waikiki, government_area=Primary Urban Center, market=Oahu, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-157.82696, 21.27971], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=302 Kanai A Nalu Ocean front/view, property_type=Condominium, address=Document{{street=Wailuku, HI, United States, suburb=Maui, government_area=Kihei-Makena, market=Maui, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-156.5039, 20.79664], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=Sugar Beach Resort 1BR Ground Floor Condo !, property_type=Condominium, address=Document{{street=Kihei, HI, United States, suburb=Maui, government_area=Kihei-Makena, market=Maui, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-156.46697, 20.78484], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=2 BR Oceanview - Great Location!, property_type=Condominium, address=Document{{street=Kihei, HI, United States, suburb=Kihei/Wailea, government_area=Kihei-Makena, market=Maui, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-156.44917, 20.73013], is_location_exact=true}}}}, score=2.238388776779175}}
Document{{name=PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC, property_type=Condominium, address=Document{{street=Kihei, HI, United States, suburb=Maui, government_area=Kihei-Makena, market=Maui, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-156.4409, 20.69735], is_location_exact=true}}}}, score=2.238388776779175}}

다음 코드 예제에서는:

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

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

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

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri ="<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 await client.connect();
11
12 // set namespace
13 const database = client.db("sample_airbnb");
14 const coll = database.collection("listingsAndReviews");
15
16 // define pipeline
17 const agg = [
18 {
19 '$search': {
20 'index': '<INDEX-NAME>',
21 'compound': {
22 'must': [
23 {
24 'geoWithin': {
25 'geometry': {
26 'type': 'Polygon',
27 'coordinates': [
28 [
29 [
30 -161.323242, 22.512557
31 ], [
32 -152.446289, 22.065278
33 ], [
34 -156.09375, 17.811456
35 ], [
36 -161.323242, 22.512557
37 ]
38 ]
39 ]
40 },
41 'path': 'address.location'
42 }
43 }
44 ],
45 'should': [
46 {
47 'text': {
48 'path': 'property_type',
49 'query': 'Condominium'
50 }
51 }
52 ]
53 }
54 }
55 }, {
56 '$limit': 10
57 }, {
58 '$project': {
59 '_id': 0,
60 'name': 1,
61 'address': 1,
62 'property_type': 1,
63 'score': {
64 '$meta': 'searchScore'
65 }
66 }
67 }
68 ];
69 // run pipeline
70 const result = await coll.aggregate(agg);
71
72 // print results
73 await result.forEach((doc) => console.log(doc));
74 } finally {
75 await client.close();
76 }
77}
78run().catch(console.dir);

다음 코드 예제에서는:

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

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

    • 복합 $search 단계를 사용하여 다음을 수행합니다.

      • 결과 mustcoordinates 세트에 의해 정의된 Polygon 내에 포함되도록 지정합니다.

      • condominium 유형의 속성에 대한 결과에 우선 순위를 부여합니다.

    • $project 단계를 사용하여 다음을 수행합니다.

      • name, addressproperty_type 를 제외한 모든 필드를 제외합니다.

      • 반환된 각 문서에 관련성 score 을 추가합니다.

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

1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient('<connection-string>')
5
6# define pipeline
7pipeline = [
8 {
9 '$search': {
10 'index': '<INDEX-NAME>',
11 'compound': {
12 'must': [
13 {
14 'geoWithin': {
15 'geometry': {
16 'type': 'Polygon',
17 'coordinates': [
18 [
19 [
20 -161.323242, 22.512557
21 ], [
22 -152.446289, 22.065278
23 ], [
24 -156.09375, 17.811456
25 ], [
26 -161.323242, 22.512557
27 ]
28 ]
29 ]
30 },
31 'path': 'address.location'
32 }
33 }
34 ],
35 'should': [
36 {
37 'text': {
38 'path': 'property_type',
39 'query': 'Condominium'
40 }
41 }
42 ]
43 }
44 }
45 }, {
46 '$limit': 10
47 }, {
48 '$project': {
49 '_id': 0,
50 'name': 1,
51 'address': 1,
52 'property_type': 1,
53 'score': {
54 '$meta': 'searchScore'
55 }
56 }
57 }
58]
59# run pipeline
60result = client["sample_airbnb"]["listingsAndReviews"].aggregate(pipeline)
61
62# print results
63for i in result:
64 print(i)
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Primary Urban Center",
"location": {
"coordinates": [
-157.83919,
21.28634
],
"is_location_exact": true,
"type": "Point"
},
"market": "Oahu",
"street": "Honolulu, HI, United States",
"suburb": "O\u02bbahu"
},
"name": "Ocean View Waikiki Marina w/prkg",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Lahaina",
"location": {
"coordinates": [
-156.68012,
20.96996
],
"is_location_exact": true,
"type": "Point"
},
"market": "Maui",
"street": "Lahaina, HI, United States",
"suburb": "Maui"
},
"name": "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Waianae",
"location": {
"coordinates": [
-158.20291,
21.4818
],
"is_location_exact": true,
"type": "Point"
},
"market": "Oahu",
"street": "Waianae, HI, United States",
"suburb": "Leeward Side"
},
"name": "Makaha Valley Paradise with OceanView",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Kihei-Makena",
"location": {
"coordinates": [
-156.46881,
20.78621
],
"is_location_exact": true,
"type": "Point"
},
"market": "Maui",
"street": "Kihei, HI, United States",
"suburb": "Maui"
},
"name": "March 2019 availability! Oceanview on Sugar Beach!",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "South Hilo",
"location": {
"coordinates": [
-155.09259,
19.73108
],
"is_location_exact": true,
"type": "Point"
},
"market": "The Big Island",
"street": "Hilo, HI, United States",
"suburb": "Island of Hawai\u02bbi"
},
"name": "Tropical Jungle Oasis",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Primary Urban Center",
"location": {
"coordinates": [
-157.82696,
21.27971
],
"is_location_exact": true,
"type": "Point"
},
"market": "Oahu",
"street": "Honolulu, HI, United States",
"suburb": "Waikiki"
},
"name": "2 Bdrm/2 Bath Family Suite Ocean View",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Kihei-Makena",
"location": {
"coordinates": [
-156.5039,
20.79664
],
"is_location_exact": true,
"type": "Point"
},
"market": "Maui",
"street": "Wailuku, HI, United States",
"suburb": "Maui"
},
"name": "302 Kanai A Nalu Ocean front/view",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Kihei-Makena",
"location": {
"coordinates": [
-156.46697,
20.78484
],
"is_location_exact": true,
"type": "Point"
},
"market": "Maui",
"street": "Kihei, HI, United States",
"suburb": "Maui"
},
"name": "Sugar Beach Resort 1BR Ground Floor Condo !",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Kihei-Makena",
"location": {
"coordinates": [
-156.44917,
20.73013
],
"is_location_exact": true,
"type": "Point"
},
"market": "Maui",
"street": "Kihei, HI, United States",
"suburb": "Kihei/Wailea"
},
"name": "2 BR Oceanview - Great Location!",
"property_type": "Condominium",
"score": 2.238388776779175
}
{
"address": {
"country": "United States",
"country_code": "US",
"government_area": "Kihei-Makena",
"location": {
"coordinates": [
-156.4409,
20.69735
],
"is_location_exact": true,
"type": "Point"
},
"market": "Maui",
"street": "Kihei, HI, United States",
"suburb": "Maui"
},
"name": "PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC",
"property_type": "Condominium",
"score": 2.238388776779175
}

다음 예시에서는 geometry 필드와 함께 geoWithin 연산자를 사용하여 하와이의 속성을 검색합니다. type 필드는 해당 영역이 GeoJSON 다각형인지 다중 다각형인지를 지정합니다.

쿼리에는 다음이 포함됩니다.

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

  • nameaddress를 제외한 모든 필드를 제외하려면 $project 단계를 수행합니다.

참고

Atlas Search 검색 쿼리에 default 이라는 인덱스를 지정할 필요가 없습니다. 인덱스에 다른 이름이 있는 경우 index 필드를 지정해야 합니다.

1db.listingsAndReviews.aggregate([
2 {
3 "$search": {
4 "geoWithin": {
5 "geometry": {
6 "type": "MultiPolygon",
7 "coordinates": [
8 [[[-157.8412413882,21.2882235819],
9 [-157.8607925468,21.2962046205],
10 [-157.8646640634,21.3077019651],
11 [-157.862776699,21.320776283],
12 [-157.8341758705,21.3133826738],
13 [-157.8349985678,21.3000822569],
14 [-157.8412413882,21.2882235819]]],
15 [[[-157.852898124,21.301208833],
16 [-157.8580050499,21.3050871833],
17 [-157.8587346108,21.3098050385],
18 [-157.8508811028,21.3119240258],
19 [-157.8454308541,21.30396767],
20 [-157.852898124,21.301208833]]]
21 ]
22 },
23 "path": "address.location"
24 }
25 }
26 },
27 {
28 $limit: 3
29 },
30 {
31 $project: {
32 "_id": 0,
33 "name": 1,
34 "address": 1
35 }
36 }
37])
{
"name" : "Heart of Honolulu, 2BD gem! Free Garage Parking!",
"address" : {
"street" : "Honolulu, HI, United States",
"suburb" : "Makiki/Lower Punchbowl/Tantalus",
"government_area" : "Primary Urban Center",
"market" : "Oahu",
"country" : "United States",
"country_code" : "US",
"location" : {
"type" : "Point",
"coordinates" : [ -157.84343, 21.30852 ],
"is_location_exact" : false
}
}
}
{
"name" : "Private Studio closed to town w/ compact parking",
"address" : {
"street" : "Honolulu, HI, United States",
"suburb" : "Oʻahu",
"government_area" : "Primary Urban Center",
"market" : "Oahu",
"country" : "United States",
"country_code" : "US",
"location" : {
"type" : "Point",
"coordinates" : [ -157.85228, 21.31184 ],
"is_location_exact" : true
}
}
}
{
"name" : "Comfortable Room (2) at Affordable Rates",
"address" : {
"street" : "Honolulu, HI, United States",
"suburb" : "Oʻahu",
"government_area" : "Primary Urban Center",
"market" : "Oahu",
"country" : "United States",
"country_code" : "US",
"location" : {
"type" : "Point",
"coordinates" : [ -157.83889, 21.29776 ],
"is_location_exact" : false
}
}
}

돌아가기

geoShape

이 페이지의 내용