Menu Docs
Página inicial do Docs
/
MongoDB Atlas
/ /

Como executar uma query JSON geográfica composta do Atlas Search

Nesta página

  • Crie o Índice Atlas Search
  • Executar uma query combinada de campos geográficos, numéricos e de texto

Este tutorial descreve como criar um índice na collection listingsAndReviews no reconhecimento de data center sample_airbnb e executar uma query que retorna documento com o name, address e property_type para cada propriedade dentro do especificado polígono definido usando coordinates.

Este tutorial orienta você pelas seguintes etapas:

  1. Defina um índice do Atlas Search no address campo na coleção sample_airbnb.listingsAndReviews.

  2. Execute uma query que retorna 10 documentos com o name, address e property_type de cada propriedade dentro do coordinates geográfico especificado. Os resultados do Atlas Search refletem uma preferência pelas propriedades do tipo condominium, e cada documento no resultado é atribuído a uma relevância score, retornado em ordem do mais alto para o mais baixo.

Antes de começar, certifique-se de que seu Atlas cluster atenda aos requisitos descritos nos pré-requisitos do .

Para criar um índice do Atlas Search, você deve ter acesso do Project Data Access Admin ou superior ao projeto.

Nesta seção, você criará um índice de pesquisa do Atlas Search no campo address na collection sample_airbnb.listingsAndReviews .

1
  1. Se ainda não estiver exibido, selecione a organização que contém o projeto desejado no Menu Organizations na barra de navegação.

  2. Se ainda não estiver exibido, selecione o projeto desejado no menu Projects na barra de navegação.

  3. Se a página Clusters ainda não estiver exibida, clique em Database na barra lateral.

2

Você pode acessar a página Atlas Search na barra lateral, o Data Explorer ou a página de detalhes do cluster.

  1. Na barra lateral, clique em Atlas Search sob o título Services .

  2. Na lista suspensa Select data source , selecione seu cluster e clique em Go to Atlas Search.

  1. Clique no botão Browse Collections para o seu cluster.

  2. Expanda o banco de dados e selecione a coleção.

  3. Clique na aba Search Indexes da collection.

  1. Clique no nome do cluster.

  2. Clique na aba Atlas Search.

3
4
  • Para uma experiência abada, selecione a Pesquisa Atlas Visual Editor.

  • Para editar a definição de índice bruto, selecione a Pesquisa Atlas JSON Editor.

5
  1. No campo Index Name, digite default.

    Observação

    Se você nomear seu índice como default, não precisará especificar um parâmetro index ao usar o estágio do pipeline $search. Caso contrário, você deve especificar o nome do índice utilizando o parâmetro index.

  2. Na seção Database and Collection, localize o banco de dados sample_mflix e selecione a coleção movies.

6

Você pode usar o Visual Editor do Atlas Search ou o JSON Editor do Atlas Search na interface de usuário do Atlas para criar o índice. A seguinte definição de índice especifica que o Atlas Search deve indexar:

  • Todos os campos da collection automaticamente.

  • O campo address.location de um document como tipo geo .

  1. Clique em Next.

  2. Clique em Refine Your Index.

  3. Na seção Field Mappings, clique em Add Field.

  4. Selecione address.location no menu suspenso Field Name.

  5. Clique no menu suspenso Data Type e selecione Geo.

  6. Clique em Add.

  7. Clique em Save Changes.

  1. Substitua a definição de índice padrão pela seguinte definição de índice de exemplo.

    {
    "mappings": {
    "dynamic": true,
    "fields": {
    "address": {
    "fields": {
    "location": {
    "type": "geo"
    }
    },
    "type": "document"
    }
    }
    }
    }
  2. Clique em Next.

7
8

Uma janela modal é exibida para que você saiba que seu índice está construindo. Clique no botão Close.

9

O índice deve levar cerca de um minuto para ser criado. Enquanto está se formando, a coluna Status mostra Build in Progress. Quando terminar de se formar, a coluna Status mostrará Active.


➤ Use o menu suspenso Selecione seu idioma nesta página para definir o idioma dos exemplos nesta seção.


Nesta seção, você executará uma query que retorna 10 documentos com o name , address e property_type para cada propriedade dentro do coordinates geográfico especificado. Um campo especificando cada documento score também é retornado e os resultados são ordenados com preferência para propriedades do tipo condominium.

1
  1. Se ainda não estiver exibido, selecione a organização que contém o projeto desejado no Menu Organizations na barra de navegação.

  2. Se ainda não estiver exibido, selecione o projeto desejado no menu Projects na barra de navegação.

  3. Se a página Clusters ainda não estiver exibida, clique em Database na barra lateral.

2

Você pode acessar a página Atlas Search na barra lateral, o Data Explorer ou a página de detalhes do cluster.

  1. Na barra lateral, clique em Atlas Search sob o título Services .

  2. Na lista suspensa Select data source , selecione seu cluster e clique em Go to Atlas Search.

  1. Clique no botão Browse Collections para o seu cluster.

  2. Expanda o banco de dados e selecione a coleção.

  3. Clique na aba Search Indexes da collection.

  1. Clique no nome do cluster.

  2. Clique na aba Atlas Search.

3

Clique no botão Query à direita do índice para consultar.

4

Clique em Edit Query para visualizar uma amostra de sintaxe de consulta padrão no formato JSON .

5

A seguinte query de pesquisa do Atlas Search usa o operador composto para:

  • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

  • Dê preferência aos resultados das propriedades do tipo condominium.

Observação

O Search Tester pode não exibir todos os campos nos documentos que ele retorna. Para exibir todos os campos, incluindo o campo que você especifica no caminho da consulta, expanda o documento nos resultados.

[
{
"$search": {
"index": "geo-json-tutorial",
"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"
2 listing_url: "https://www.airbnb.com/rooms/1001265"
3 name: "Ocean View Waikiki Marina w/prkg"
4 summary: "A short distance from Honolulu's billion dollar mall,
5 and the same dis…"
6 ...
7 property_type: "Condominium"
8 ...
9 address: 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"
25 listing_url: "https://www.airbnb.com/rooms/10227000"
26 name: "LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!"
27 summary: "THIS IS A VERY SPACIOUS 1 BEDROOM FULL CONDO (SLEEPS 4) AT THE BEAUTIF…"
28 ...
29 property_type: "Condominium"
30 ...
31 address: 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"
47 listing_url: "https://www.airbnb.com/rooms/10266175"
48 name: "Makaha Valley Paradise with OceanView"
49 summary: "A beautiful and comfortable 1 Bedroom Air Conditioned Condo in Makaha …"
50 ...
51 property_type: "Condominium"
52 ...
53 address: 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"
69 listing_url: "https://www.airbnb.com/rooms/1042446"
70 name: "March 2019 availability! Oceanview on Sugar Beach!"
71 summary: ""
72 ...
73 property_type: "Condominium"
74 ...
75 address: 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"
91 listing_url: "https://www.airbnb.com/rooms/10527243"
92 name: "Tropical Jungle Oasis"
93 summary: "2 bedrooms, one with a queen sized bed, one with 2 single beds. 1 and …"
94 ...
95 property_type: "Condominium"
96 ...
97 address: 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"
113 listing_url: "https://www.airbnb.com/rooms/1104768"
114 name: "2 Bdrm/2 Bath Family Suite Ocean View"
115 summary: "This breathtaking 180 degree view of Waikiki is one of a kind. You wil…"
116 ...
117 property_type: "Condominium"
118 ...
119 address: 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"
135 listing_url: "https://www.airbnb.com/rooms/11207193"
136 name: "302 Kanai A Nalu Ocean front/view"
137 summary: "Welcome to Kana'i A Nalu a quiet resort that sits on the ocean away fr…"
138 ...
139 property_type: "Condominium"
140 ...
141 address: 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"
157 listing_url: "https://www.airbnb.com/rooms/11319047"
158 name: "Sugar Beach Resort 1BR Ground Floor Condo !"
159 summary: "The Sugar Beach Resort enjoys a beachfront setting fit for a postcard."
160 ...
161 property_type: "Condominium"
162 ...
163 address: 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"
179 listing_url: "https://www.airbnb.com/rooms/11695887"
180 name: "2 BR Oceanview - Great Location!"
181 summary: "Location, location, location... This is a great 2 bed, 2 bath condo is…"
182 ...
183 property_type: "Condominium"
184 ...
185 address: 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"
201 listing_url: "https://www.airbnb.com/rooms/11817249"
202 name: "PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC"
203 summary: "Book with confidence this stunning 2 bedroom, 2 bathroom condo at the …"
204 ...
205 property_type: "Condominium"
206 ...
207 address: 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 ...
1

Abra o mongosh em uma janela do terminal e conecte ao seu cluster. Para obter instruções detalhadas sobre a conexão, consulte Conectar via mongosh.

2

Execute o seguinte comando no prompt mongosh:

use sample_airbnb
3

A seguinte query de pesquisa do Atlas Search:

  • Usa um estágio composto $search para:

    • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

    • Dê preferência aos resultados das propriedades do tipo condominium.

  • Usa um estágio $project para:

    • Excluir todos os campos, exceto name, address e property_type.

    • Adicione uma relevância score a cada documento retornado.

A query é a seguinte:

db.listingsAndReviews.aggregate([
{
"$search": {
"index": "geo-json-tutorial",
"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
}
]
1

Abra o MongoDB Compass e conecte-se ao cluster. Para obter instruções detalhadas sobre a conexão, consulte Conectar via Compass.

2

Na tela Database, clique no banco de dados sample_airbnb e, em seguida, clique na coleção listingsAndReviews.

3

A seguinte query:

  • Usa um estágio composto $search para:

    • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

    • Dê preferência aos resultados das propriedades do tipo condominium.

  • Usa um estágio $project para:

    • Excluir todos os campos, exceto name, address e property_type.

    • Adicione uma relevância score a cada documento retornado.

Para executar esta query do Atlas Search no MongoDB Compass:

  1. Clique na aba Aggregations.

  2. Clique em Select... e, em seguida, configure cada um dos seguintes estágios do pipeline, selecionando o estágio no menu suspenso e adicionando a consulta para esse estágio. Clique em Add Stage para adicionar estágios adicionais.

    estágio do pipeline
    Query
    $search
    {
    'index': 'geo-json-tutorial',
    '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'
    }
    }

Se você habilitou o Auto Preview, o MongoDB Compass exibe os seguintes documentos ao lado da etapa de pipeline do $project:

1{
2 name: 'Ocean View Waikiki Marina w/prkg',
3 property_type: 'Condominium',
4 address: {
5 street: 'Honolulu, HI, United States',
6 suburb: 'Oʻahu',
7 government_area: 'Primary Urban Center',
8 market: 'Oahu',
9 country: 'United States',
10 country_code: 'US',
11 location: {
12 type: 'Point',
13 coordinates: [ -157.83919, 21.28634 ],
14 is_location_exact: true
15 }
16 },
17 score: 2.238388776779175
18},
19{
20 name: 'LAHAINA, MAUI! RESORT/CONDO BEACHFRONT!! SLEEPS 4!',
21 property_type: 'Condominium',
22 address: {
23 street: 'Lahaina, HI, United States',
24 suburb: 'Maui',
25 government_area: 'Lahaina',
26 market: 'Maui',
27 country: 'United States',
28 country_code: 'US',
29 location: {
30 type: 'Point',
31 coordinates: [ -156.68012, 20.96996 ],
32 is_location_exact: true
33 }
34 },
35 score: 2.238388776779175
36},
37{
38 name: 'Makaha Valley Paradise with OceanView',
39 property_type: 'Condominium',
40 address: {
41 street: 'Waianae, HI, United States',
42 suburb: 'Leeward Side',
43 government_area: 'Waianae',
44 market: 'Oahu',
45 country: 'United States',
46 country_code: 'US',
47 location: {
48 type: 'Point',
49 coordinates: [ -158.20291, 21.4818 ],
50 is_location_exact: true
51 }
52 },
53 score: 2.238388776779175
54},
55{
56 name: 'March 2019 availability! Oceanview on Sugar Beach!',
57 property_type: 'Condominium',
58 address: {
59 street: 'Kihei, HI, United States',
60 suburb: 'Maui',
61 government_area: 'Kihei-Makena',
62 market: 'Maui',
63 country: 'United States',
64 country_code: 'US',
65 location: {
66 type: 'Point',
67 coordinates: [ -156.46881, 20.78621 ],
68 is_location_exact: true
69 }
70 },
71 score: 2.238388776779175
72},
73{
74 name: 'Tropical Jungle Oasis',
75 property_type: 'Condominium',
76 address: {
77 street: 'Hilo, HI, United States',
78 suburb: 'Island of Hawaiʻi',
79 government_area: 'South Hilo',
80 market: 'The Big Island',
81 country: 'United States',
82 country_code: 'US',
83 location: {
84 type: 'Point',
85 coordinates: [ -155.09259, 19.73108 ],
86 is_location_exact: true
87 }
88 },
89 score: 2.238388776779175
90},
91{
92 name: '2 Bdrm/2 Bath Family Suite Ocean View',
93 property_type: 'Condominium',
94 address: {
95 street: 'Honolulu, HI, United States',
96 suburb: 'Waikiki',
97 government_area: 'Primary Urban Center',
98 market: 'Oahu',
99 country: 'United States',
100 country_code: 'US',
101 location: {
102 type: 'Point',
103 coordinates: [ -157.82696, 21.27971 ],
104 is_location_exact: true
105 }
106 },
107 score: 2.238388776779175
108},
109{
110 name: '302 Kanai A Nalu Ocean front/view',
111 property_type: 'Condominium',
112 address: {
113 street: 'Wailuku, HI, United States',
114 suburb: 'Maui',
115 government_area: 'Kihei-Makena',
116 market: 'Maui',
117 country: 'United States',
118 country_code: 'US',
119 location: {
120 type: 'Point',
121 coordinates: [ -156.5039, 20.79664 ],
122 is_location_exact: true
123 }
124 },
125 score: 2.238388776779175
126},
127{
128 name: 'Sugar Beach Resort 1BR Ground Floor Condo !',
129 property_type: 'Condominium',
130 address: {
131 street: 'Kihei, HI, United States',
132 suburb: 'Maui',
133 government_area: 'Kihei-Makena',
134 market: 'Maui',
135 country: 'United States',
136 country_code: 'US',
137 location: {
138 type: 'Point',
139 coordinates: [ -156.46697, 20.78484 ],
140 is_location_exact: true
141 }
142 },
143 score: 2.238388776779175
144},
145{
146 name: '2 BR Oceanview - Great Location!',
147 property_type: 'Condominium',
148 address: {
149 street: 'Kihei, HI, United States',
150 suburb: 'Kihei/Wailea',
151 government_area: 'Kihei-Makena',
152 market: 'Maui',
153 country: 'United States',
154 country_code: 'US',
155 location: {
156 type: 'Point',
157 coordinates: [ -156.44917, 20.73013 ],
158 is_location_exact: true
159 }
160 },
161 score: 2.238388776779175
162},
163{
164 name: 'PALMS AT WAILEA #905-2BR-REMODELED-LARGE LANAI-AC',
165 property_type: 'Condominium',
166 address: {
167 street: 'Kihei, HI, United States',
168 suburb: 'Maui',
169 government_area: 'Kihei-Makena',
170 market: 'Maui',
171 country: 'United States',
172 country_code: 'US',
173 location: {
174 type: 'Point',
175 coordinates: [ -156.4409, 20.69735 ],
176 is_location_exact: true
177 }
178 },
179 score: 2.238388776779175
180}

Para obter mais informações sobre o estágio do pipeline $search, consulte sua página de referência. Para obter a documentação completa do pipeline de agregação, consulte o Manual do MongoDB Server.

1
  1. Crie um novo diretório denominado combined-geo-query e inicialize seu projeto com o comando dotnet new.

    mkdir combined-geo-query
    cd combined-geo-query
    dotnet new console
  2. Adicione o driver .NET/C# ao seu projeto como uma dependência.

    dotnet add package MongoDB.Driver
2
  1. Substitua o conteúdo do arquivo Program.cs pelo seguinte código.

    A seguinte query de pesquisa do Atlas Search:

    • Usa um estágio composto $search para:

      • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

      • Dê preferência aos resultados das propriedades do tipo condominium.

    • Usa um estágio $project para:

      • Excluir todos os campos, exceto name, address e property_type.

      • Adicione uma relevância score a cada documento retornado.

    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: "geo-json-tutorial")
    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}
  2. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

3
dotnet run combined-geo-query.csproj
{
"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
}
1
2

O seguinte exemplo de código:

  • Importa pacotes e dependências do mongodb .

  • Estabelece uma ligação ao seu cluster Atlas.

  • Usa um estágio composto $search para:

    • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

    • Dê preferência aos resultados das propriedades do tipo condominium.

  • Usa um estágio $project para:

    • Excluir todos os campos, exceto name, address e property_type.

    • Adicione uma relevância score a cada documento retornado.

  • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 // connect to your Atlas cluster
14 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
15 if err != nil {
16 panic(err)
17 }
18 defer client.Disconnect(context.TODO())
19
20 // set namespace
21 collection := client.Database("sample_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": "geo-json-tutorial",
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}
3

Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

4
go run run-geo-query.go
[{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}]
1
junit
4.11 ou versão superior
mongodb-driver-sync
4.3.0 ou uma versão superior
slf4j-log4j12
1.7.30 ou uma versão superior
2
3

O seguinte exemplo de código:

  • Importa pacotes e dependências do mongodb .

  • Estabelece uma ligação ao seu cluster Atlas.

  • Usa um estágio composto $search para:

    • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

    • Dê preferência aos resultados das propriedades do tipo condominium.

  • Usa um estágio $project para:

    • Excluir todos os campos, exceto name, address e property_type.

    • Adicione uma relevância score a cada documento retornado.

  • Itera sobre o cursor para imprimir os documentos que correspondem ao
    query.
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", "geo-json-tutorial")
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}

Observação

Para executar o código de amostra em seu ambiente Maven, adicione o seguinte acima das declarações de importação em seu arquivo.

package com.mongodb.drivers;
4

Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

5
javac GeoQuery.java
java GeoQuery
{"name": "Ocean View Waikiki Marina w/prkg", "property_type": "Condominium", "address": {"street": "Honolulu, HI, United States", "suburb": "O\u02bbahu", "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": 1.0},
{"name": "Kailua-Kona, Kona Coast II 2b condo", "property_type": "Apartment", "address": {"street": "Kailua-Kona, HI, United States", "suburb": "Kailua/Kona", "government_area": "North Kona", "market": "The Big Island", "country": "United States", "country_code": "US", "location": {"type": "Point", "coordinates": [-155.96445, 19.5702], "is_location_exact": true}}, "score": 1.0},
{"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": 1.0},
{"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": 1.0},
{"name": "~Ao Lele~ Flying Cloud", "property_type": "Treehouse", "address": {"street": "Volcano, HI, United States", "suburb": "Island of Hawai\u02bbi", "government_area": "Puna", "market": "The Big Island", "country": "United States", "country_code": "US", "location": {"type": "Point", "coordinates": [-155.21763, 19.42151], "is_location_exact": false}}, "score": 1.0},
{"name": "Private OceanFront - Bathtub Beach. Spacious House", "property_type": "House", "address": {"street": "Laie, HI, United States", "suburb": "Ko'olauloa", "government_area": "Koolauloa", "market": "Oahu", "country": "United States", "country_code": "US", "location": {"type": "Point", "coordinates": [-157.91952, 21.63549], "is_location_exact": true}}, "score": 1.0},
{"name": "Banyan Bungalow", "property_type": "Bungalow", "address": {"street": "Waialua, HI, United States", "suburb": "O\u02bbahu", "government_area": "North Shore Oahu", "market": "Oahu", "country": "United States", "country_code": "US", "location": {"type": "Point", "coordinates": [-158.1602, 21.57561], "is_location_exact": false}}, "score": 1.0},
{"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": 1.0},
{"name": "Tropical Jungle Oasis", "property_type": "Condominium", "address": {"street": "Hilo, HI, United States", "suburb": "Island of Hawai\u02bbi", "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": 1.0},
{"name": "Jubilee By The Sea (Ocean Views)", "property_type": "House", "address": {"street": "Kailua-Kona, HI, United States", "suburb": "Island of Hawai\u02bbi", "government_area": "North Kona", "market": "The Big Island", "country": "United States", "country_code": "US", "location": {"type": "Point", "coordinates": [-155.97349, 19.61318], "is_location_exact": false}}, "score": 1.0}
1
mongodb-driver-kotlin-coroutine
4.10.0 ou uma versão superior
2
3

O seguinte exemplo de código:

  • Importa pacotes e dependências do mongodb .

  • Estabelece uma ligação ao seu cluster Atlas.

  • Usa um estágio composto $search para:

    • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

    • Dê preferência aos resultados das propriedades do tipo condominium.

  • Usa um estágio $project para:

    • Excluir todos os campos, exceto name, address e property_type.

    • Adicione uma relevância score a cada documento retornado.

  • Imprime os documentos que correspondem à query da instância 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", "geo-json-tutorial")
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}
4

Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

5

Ao executar o programa GeoQuery.kt no seu IDE, ele imprime os seguintes documentos:

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}}
1
2

O seguinte exemplo de código:

  • Importa mongodb, o driver do Node.js da MongoDB.

  • Cria uma instância da classe MongoClient para estabelecer uma conexão com seu cluster do Atlas.

    • Usa um estágio composto $search para:

      • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

      • Dê preferência aos resultados das propriedades do tipo condominium.

    • Usa um estágio $project para:

      • Excluir todos os campos, exceto name, address e property_type.

      • Adicione uma relevância score a cada documento retornado.

  • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    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': 'geo-json-tutorial',
    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);
3

Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

4

Execute o seguinte comando para consultar sua collection:

node run-geo-query.js
{
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
}
1
2

O seguinte exemplo de código:

  • Importa pymongo, o driver Python do MongoDB e o módulo dns , que é necessário para conectar pymongo a Atlas usando uma connection string de lista de sementes de DNS .

  • Cria uma instância da classe MongoClient para estabelecer uma conexão com seu cluster do Atlas.

    • Usa um estágio composto $search para:

      • Especifique que os resultados must estejam dentro de um Polygon definido por um conjunto de coordinates.

      • Dê preferência aos resultados das propriedades do tipo condominium.

    • Usa um estágio $project para:

      • Excluir todos os campos, exceto name, address e property_type.

      • Adicione uma relevância score a cada documento retornado.

  • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    8 {
    9 '$search': {
    10 'index': 'geo-json-tutorial',
    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)
3

Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

4
python run-geo-query.py
{
"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
}

Voltar

Insensível a sinais diacríticos

Próximo

composto