Docs Menu
Docs Home
/ /

geoWithin 演算子

geoWithin

geoWithin演算子は、指定された形状内の地理的ポイントのクエリをサポートしています。 インデックス定義indexShapesの値がtrueであっても、ポイントのみが返されます。

以下内のポイントをクエリできます。

  • 境界ボックス

  • 多角形

検索する座標を指定する場合は、最初に 経度 、次に 緯度 を指定する必要があります。 経度の値は、両方を含む-180180の間で指定できます。 緯度の値は-9090の間で指定できます。 座標値は整数または double にすることができます。

注意

MongoDB 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ポイントを指定するオブジェクト。 オブジェクトは次のフィールドを取ります。

GeoJSON オブジェクト内で GeoJSON データを指定する方法については、「 GeoJSON オブジェクト 」を参照してください。

boxcircle 、またはgeometryのいずれかが必要です。

条件付き

circle

オブジェクト

検索する中心点と半径をメートル単位で指定するオブジェクト。 オブジェクトには、次のGeoJSONフィールドが含まれています。

GeoJSON オブジェクト内で GeoJSON データを指定する方法については、「 GeoJSON オブジェクト 」を参照してください。

circlebox 、またはgeometryのいずれかが必要です。

条件付き

geometry

GeoJSON オブジェクト

検索対象の Multi ポリゴンまたは 多角形 を指定する GeoJSON オブジェクト。多角形は最後の位置が最初の位置と同じである閉じたループとして指定する必要があります。

地理空間結果を計算する場合、 MongoDB Search geoShape 演算子と geoWithin 演算子、およびMongoDB $geoIntersects 演算子は異なるジオメトリを使用します。この違いは、 MongoDB Search とMongoDB が多角形エッジを描画する方法で確認できます。

MongoDB Search は、座標参照システム内の 2 点間の最小ラインである直列距離 に基づいて多角形を描画します。

MongoDB は、 ジオメトリ タイプ のサードパーティ ライブラリ上に構築された2 dsphere インデックス 、または 平面モードに基づきジオデックスモードを使用して多角形を読み込み、2 d インデックス から収集します。詳細については、 「GeoJSON オブジェクト」 を参照してください。

MongoDB Search とMongoDBでは、多角形に関係する地理空間クエリで異なる結果が返される可能性がありました。

GeoJSON オブジェクト内で GeoJSON データを指定する方法については、「 GeoJSON オブジェクト 」を参照してください。

geometrybox 、またはcircleのいずれかが必要です。

条件付き

path

文字列または複数の文字列の配列

検索するインデックス付き geo 型フィールド。

はい

score

オブジェクト

一致する検索結果に割り当てる スコア 。 デフォルトでは、結果のスコア1です。 次のオプションを使用してスコアを変更できます。

  • boost: 結果のスコアに指定された数値を掛けます。

  • constant: 結果のスコアを指定された数値に置き換えます。

  • function: 結果のスコアを指定された式で置き換えます。

クエリで score を使用する方法については、「結果内のドキュメントのスコアリング」を参照してください。

no

次の例では、 sample_airbnbデータベース内の listingsAndReviewsコレクションを使用します。クラスターにサンプルデータセットがある場合は、ジオタイプ用のカスタムMongoDB Searchインデックスを作成し、クラスターで例クエリを実行できます。

次のサンプル インデックス定義を使用して、 listingsAndReviewsコレクションの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の結果に制限します。

  • $projectステージでは、 nameaddressを除くすべてのフィールドが除外されます。

注意

MongoDB Search クエリに default という名前のインデックスを指定する必要はありません。インデックスに他の名前がある場合は、indexフィールドを指定する必要があります。

次のMongoDB Search クエリは、指定された検索条件に一致するドキュメントを返します。

{
"$search": {
"geoWithin": {
"path": "address.location",
"box": {
"bottomLeft": {
"type": "Point",
"coordinates": [112.467, -55.050]
},
"topRight": {
"type": "Point",
"coordinates": [168.000, -9.133]
}
}
}
}
}
1SCORE: 1 _id: “10091713
2 access: "You have full use of the entire studio and complete privacy during you…"
3 accommodates: 2
4 address: Object
5 street: "Surry Hills, NSW, Australia"
6 suburb: "Darlinghurst"
7 government_area: "Sydney"
8 market: "Sydney"
9 country: "Australia"
10 country_code: "AU"
11 location: Object
12 type: "Point"
13 coordinates: Array (2)
14 0: 151.21554
15 1: -33.88029
16 is_location_exact: true
17
18SCORE: 1 _id: “10108388
19 access: "SECURITY Secure 24hour front-desk access with full access to the roof…"
20 accommodates: 2
21 address: Object
22 street: "Darlinghurst, NSW, Australia"
23 suburb: "Darlinghurst"
24 government_area: "Sydney"
25 market: "Sydney"
26 country: "Australia"
27 country_code: "AU"
28 location: Object
29 type: "Point"
30 coordinates: Array (2)
31 0: 151.21346
32 1: -33.87603
33 is_location_exact: false
34
35SCORE: 1 _id: “10109896
36 access: "You'll access all areas except the master bedroom and spare bedrooms, …"
37 accommodates: 2
38 address: Object
39 street: "Rozelle, NSW, Australia"
40 suburb: "Lilyfield/Rozelle"
41 government_area: "Leichhardt"
42 market: "Sydney"
43 country: "Australia"
44 country_code: "AU"
45 location: Object
46 type: "Point"
47 coordinates: Array (2)
48 0: 151.17956
49 1: -33.86296
50 is_location_exact: true
51
52SCORE: 1 _id: “1016739
53 access: "Included in the price is unlimited wifi, Kitchen facilities, Laundry f…"
54 accommodates: 2
55 address: Object
56 street: "Coogee, NSW, Australia"
57 suburb: "Coogee"
58 government_area: "Randwick"
59 market: "Sydney"
60 country: "Australia"
61 country_code: "AU"
62 location: Object
63 type: "Point"
64 coordinates: Array (2)
65 0: 151.25541
66 1: -33.92398
67 is_location_exact: true
68
69SCORE: 1 _id: “10209136
70 access: "You will have access to kitchen, bathroom, lounge room, separate laund…"
71 accommodates: 2
72 address: Object
73 street: "Fairlight, NSW, Australia"
74 suburb: "Fairlight"
75 government_area: "Manly"
76 market: "Sydney"
77 country: "Australia"
78 country_code: "AU"
79 location: Object
80 type: "Point"
81 coordinates: Array (2)
82 0: 151.26969
83 1: -33.79629
84 is_location_exact: false
85
86SCORE: 1 _id: “10213499
87 access: "Guests have access to backyard saltwater pool"
88 accommodates: 2
89 address: Object
90 street: "Narrabeen, NSW, Australia"
91 suburb: ""
92 government_area: "Warringah"
93 market: "Sydney"
94 country: "Australia"
95 country_code: "AU"
96 location: Object
97 type: "Point"
98 coordinates: Array (2)
99 0: 151.29792
100 1: -33.71472
101 is_location_exact: true
102
103SCORE: 1 _id: “10416859
104 access: "There is a private, external entrance to your room. And there are sta…"
105 accommodates: 5
106 address: Object
107 street: "Balgowlah, NSW, Australia"
108 suburb: "Balgowlah"
109 government_area: "Manly"
110 market: "Sydney"
111 country: "Australia"
112 country_code: "AU"
113 location: Object
114 type: "Point"
115 coordinates: Array (2)
116 0: 151.26108
117 1: -33.7975
118 is_location_exact: true
119
120SCORE: 1 _id: “10423504
121 access: "The house has a front deck and back garden area. I can be flexible wi…"
122 accommodates: 8
123 address: Object
124 street: "Bondi Beach, NSW, Australia"
125 suburb: "Bondi Beach"
126 government_area: "Waverley"
127 market: "Sydney"
128 country: "Australia"
129 country_code: "AU"
130 location: Object
131 type: "Point"
132 coordinates: Array (2)
133 0: 151.27448
134 1: -33.8872
135 is_location_exact: false
136
137SCORE: 1 _id: “10459480
138 access: "Complete home."
139 accommodates: 6
140 address: Object
141 street: "Greenwich, NSW, Australia"
142 suburb: "Greenwich"
143 government_area: "Lane Cove"
144 market: "Sydney"
145 country: "Australia"
146 country_code: "AU"
147 location: Object
148 type: "Point"
149 coordinates: Array (2)
150 0: 151.18563
151 1: -33.8289
152 is_location_exact: true
153
154SCORE: 1 _id: “1047087
155 access: "Guests come in to the studio using their own access via a side path. G…"
156 accommodates: 2
157 address: Object
158 street: "Marrickville, NSW, Australia"
159 suburb: "Marrickville"
160 government_area: "Marrickville"
161 market: "Sydney"
162 country: "Australia"
163 country_code: "AU"
164 location: Object
165 type: "Point"
166 coordinates: Array (2)
167 0: 151.15036
168 1: -33.90318
169 is_location_exact: false
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
}
}
}
]

MongoDB Compass で次のクエリを実行する方法については、「クエリを定義する」を参照してください。

パイプラインステージ
クエリ

$search

{
"geoWithin": {
"path": "address.location",
"box": {
"bottomLeft": {
"type": "Point",
"coordinates": [112.467, -55.050]
},
"topRight": {
"type": "Point",
"coordinates": [168.000, -9.133]
}
}
}
}

$limit

3

$project

{
"_id": 0,
"name": 1,
"address": 1
}
{
"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
}
}
}
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.GeoJsonObjectModel;
6using MongoDB.Driver.Search;
7
8public class GeoBoxQuery
9{
10 // Make sure your password is URL encoded if it contains special characters
11 // Replace with your actual connection string with correct credentials
12 private const string MongoConnectionString = "<connection-string>";
13
14 public static void Main(string[] args)
15 {
16 // allow automapping of the camelCase database fields to our PropertyDocument
17 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
18 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
19
20 // connect to your Atlas cluster
21 var mongoClient = new MongoClient(MongoConnectionString);
22 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
23 var listingsCollection = airbnbDatabase.GetCollection<PropertyDocument>("listingsAndReviews");
24
25 // define and run pipeline
26 var results = listingsCollection.Aggregate()
27 .Search(Builders<PropertyDocument>.Search.GeoWithin(
28 property => property.Address!.Location,
29 new GeoWithinBox<GeoJson2DCoordinates>(
30 new GeoJsonPoint<GeoJson2DCoordinates>(new GeoJson2DCoordinates(112.467, -55.050)),
31 new GeoJsonPoint<GeoJson2DCoordinates>(new GeoJson2DCoordinates(168.000, -9.133))
32 )
33 ))
34 .Limit(3)
35 .Project<PropertyDocument>(Builders<PropertyDocument>.Projection
36 .Include(property => property.Name)
37 .Include(property => property.Address)
38 .Exclude(property => property.Id))
39 .ToList();
40
41 // print results
42 foreach (var property in results)
43 {
44 Console.WriteLine(property.ToJson());
45 }
46 }
47}
48
49[BsonIgnoreExtraElements]
50public class PropertyDocument
51{
52 [BsonIgnoreIfDefault]
53 public ObjectId Id { get; set; }
54 public string? Name { get; set; }
55 public AddressDocument? Address { get; set; }
56}
57
58[BsonIgnoreExtraElements]
59public class AddressDocument
60{
61 public GeoJsonPoint<GeoJson2DCoordinates>? Location { get; set; }
62 public string? Street { get; set; }
63 public string? Country { get; set; }
64}
{ "name" : "Surry Hills Studio - Your Perfect Base in Sydney", "address" : { "location" : { "type" : "Point", "coordinates" : [151.21554, -33.880290000000002], "is_location_exact" : true }, "street" : "Surry Hills, NSW, Australia", "country" : "Australia" } }
{ "name" : "Sydney Hyde Park City Apartment (checkin from 6am)", "address" : { "location" : { "type" : "Point", "coordinates" : [151.21346, -33.87603], "is_location_exact" : false }, "street" : "Darlinghurst, NSW, Australia", "country" : "Australia" } }
{ "name" : "THE Place to See Sydney's FIREWORKS", "address" : { "location" : { "type" : "Point", "coordinates" : [151.17956000000001, -33.862960000000001], "is_location_exact" : true }, "street" : "Rozelle, NSW, Australia", "country" : "Australia" } }
1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13// define structure of listingsAndReviews collection
14type Property struct {
15 Name string `bson:"name"`
16 Address struct {
17 Location struct {
18 Type string `bson:"type"`
19 Coordinates []float64 `bson:"coordinates"`
20 } `bson:"location"`
21 Street string `bson:"street"`
22 Country string `bson:"country"`
23 } `bson:"address"`
24}
25
26func main() {
27 var err error
28 // connect to the Atlas cluster
29 ctx := context.Background()
30 client, err := mongo.Connect(options.Client().SetTimeout(5*time.Second).ApplyURI("<connection-string>"))
31 if err != nil {
32 panic(err)
33 }
34 defer client.Disconnect(ctx)
35 // set namespace
36 collection := client.Database("sample_airbnb").Collection("listingsAndReviews")
37 // define pipeline
38 searchStage := bson.D{{Key: "$search", Value: bson.M{
39 "geoWithin": bson.M{
40 "path": "address.location",
41 "box": bson.M{
42 "bottomLeft": bson.M{
43 "type": "Point",
44 "coordinates": []float64{112.467, -55.050},
45 },
46 "topRight": bson.M{
47 "type": "Point",
48 "coordinates": []float64{168.000, -9.133},
49 },
50 },
51 },
52 }}}
53 limitStage := bson.D{{Key: "$limit", Value: 3}}
54 projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "_id", Value: 0}, {Key: "name", Value: 1}, {Key: "address", Value: 1}}}}
55 // run pipeline
56 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
57 if err != nil {
58 panic(err)
59 }
60 // print results
61 var results []Property
62 if err = cursor.All(context.TODO(), &results); err != nil {
63 panic(err)
64 }
65 for _, result := range results {
66 fmt.Println(result)
67 }
68}
{Surry Hills Studio - Your Perfect Base in Sydney {{Point [151.21554 -33.88029]} Surry Hills, NSW, Australia Australia}}
{Sydney Hyde Park City Apartment (checkin from 6am) {{Point [151.21346 -33.87603]} Darlinghurst, NSW, Australia Australia}}
{THE Place to See Sydney's FIREWORKS {{Point [151.17956 -33.86296]} Rozelle, NSW, Australia Australia}}
1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.excludeId;
5import static com.mongodb.client.model.Projections.fields;
6import static com.mongodb.client.model.Projections.include;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class GeoBoxQuery {
14 public static void main( String[] args ) {
15
16 // define query
17 Document agg = new Document("$search",
18 new Document("geoWithin",
19 new Document("path", "address.location")
20 .append("box",
21 new Document("bottomLeft",
22 new Document("type", "Point")
23 .append("coordinates", Arrays.asList(112.467, -55.050)))
24 .append("topRight",
25 new Document("type", "Point")
26 .append("coordinates", Arrays.asList(168.000, -9.133))))));
27
28 // specify connection
29 String uri = "<connection-string>";
30
31 // establish connection and set namespace
32 try (MongoClient mongoClient = MongoClients.create(uri)) {
33 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
34 MongoCollection<Document> collection = database.getCollection("listingsAndReviews");
35 // run query and print results
36 collection.aggregate(Arrays.asList(agg,
37 limit(3),
38 project(fields(excludeId(), include("name", "address")))))
39 .forEach(doc -> System.out.println(doc.toJson()));
40 }
41 }
42}
{
"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
}
}
}
1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("listingsAndReviews")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("geoWithin",
20 Document("path", "address.location")
21 .append("box",
22 Document("bottomLeft",
23 Document("type", "Point")
24 .append("coordinates", listOf(112.467, -55.050)))
25 .append("topRight",
26 Document("type", "Point")
27 .append("coordinates", listOf(168.000, -9.133)))))
28 )
29
30 // run query and print results
31 val resultsFlow = collection.aggregate<Document>(
32 listOf(
33 agg,
34 limit(3),
35 project(fields(excludeId(), include("name", "address")))
36 )
37 )
38 resultsFlow.collect { println(it) }
39 }
40 mongoClient.close()
41}
Document{{name=Surry Hills Studio - Your Perfect Base in Sydney, address=Document{{street=Surry Hills, NSW, Australia, suburb=Darlinghurst, government_area=Sydney, market=Sydney, country=Australia, country_code=AU, location=Document{{type=Point, coordinates=[151.21554, -33.88029], is_location_exact=true}}}}}}
Document{{name=Sydney Hyde Park City Apartment (checkin from 6am), address=Document{{street=Darlinghurst, NSW, Australia, suburb=Darlinghurst, government_area=Sydney, market=Sydney, country=Australia, country_code=AU, location=Document{{type=Point, coordinates=[151.21346, -33.87603], is_location_exact=false}}}}}}
Document{{name=THE Place to See Sydney's FIREWORKS, address=Document{{street=Rozelle, NSW, Australia, suburb=Lilyfield/Rozelle, government_area=Leichhardt, market=Sydney, country=Australia, country_code=AU, location=Document{{type=Point, coordinates=[151.17956, -33.86296], is_location_exact=true}}}}}}
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 'geoWithin': {
21 'path': 'address.location',
22 'box': {
23 'bottomLeft': {
24 'type': 'Point',
25 'coordinates': [112.467, -55.050]
26 },
27 'topRight': {
28 'type': 'Point',
29 'coordinates': [168.000, -9.133]
30 }
31 }
32 }
33 }
34 }, {
35 '$limit': 3
36 }, {
37 '$project': {
38 '_id': 0,
39 'name': 1,
40 'address': 1
41 }
42 }
43 ];
44
45 // run pipeline
46 const result = coll.aggregate(agg);
47
48 // print results
49 await result.forEach((doc) => console.log(doc));
50 } finally {
51 await client.close();
52 }
53}
54run().catch(console.dir);
{
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: [Array], 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: [Array], 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: [Array], is_location_exact: true }
}
}
1import pymongo
2import dns.resolver
3
4# connect to your Atlas cluster
5client = pymongo.MongoClient("<connection-string>")
6
7# define pipeline
8pipeline = [
9 {
10 "$search": {
11 "geoWithin": {
12 "path": "address.location",
13 "box": {
14 "bottomLeft": {
15 "type": "Point",
16 "coordinates": [112.467, -55.050]
17 },
18 "topRight": {
19 "type": "Point",
20 "coordinates": [168.000, -9.133]
21 }
22 }
23 }
24 }
25 },
26 {
27 "$limit": 3
28 },
29 {
30 "$project": {
31 "_id": 0,
32 "name": 1,
33 "address": 1
34 }
35 }
36]
37
38# run pipeline
39result = client.sample_airbnb.listingsAndReviews.aggregate(pipeline)
40
41# print results
42for i in result:
43 print(i)
{'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}}}

次のクエリは、指定された検索条件に対するプロパティの種類(アパート、家など)の数を返します。

{
"$searchMeta": {
"facet": {
"operator": {
"geoWithin": {
"path": "address.location",
"box": {
"bottomLeft": {
"type": "Point",
"coordinates": [112.467, -55.050]
},
"topRight": {
"type": "Point",
"coordinates": [168.000, -9.133]
}
}
}
},
"facets": {
"propertyTypeFacet": {
"type": "string",
"path": "property_type"
}
}
}
}
}
1map[
2 count:map[lowerBound:610]
3 facet:map[
4 propertyTypeFacet:map[
5 buckets:[
6 map[_id:Apartment count:334]
7 map[_id:House count:168]
8 map[_id:Townhouse count:29]
9 map[_id:Guest suite count:20]
10 map[_id:Condominium count:11]
11 map[_id:Cabin count:8]
12 map[_id:Serviced apartment count:7]
13 map[_id:Villa count:7]
14 map[_id:Bungalow count:5]
15 map[_id:Guesthouse count:5]
16 ]
17 ]
18 ]
19]
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])
map[
count:map[lowerBound:610]
facet:map[
propertyTypeFacet:map[
buckets:[
map[_id:Apartment count:334]
map[_id:House count:168]
map[_id:Townhouse count:29]
map[_id:Guest suite count:20]
map[_id:Condominium count:11]
map[_id:Cabin count:8]
map[_id:Serviced apartment count:7]
map[_id:Villa count:7]
map[_id:Bungalow count:5]
map[_id:Guesthouse count:5]
]
]
]
]

MongoDB Compass で次のクエリを実行する方法については、「クエリを定義する」を参照してください。

MongoDB Compass でこのクエリを実行するには:

  1. [ Aggregationsタブをクリックします。

  2. Select... をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次のパイプラインステージを設定します。

    パイプラインステージ
    クエリ

    $searchMeta

    {
    "facet": {
    "operator": {
    "geoWithin": {
    "path": "address.location",
    "box": {
    "bottomLeft": {
    "type": "Point",
    "coordinates": [112.467, -55.050]
    },
    "topRight": {
    "type": "Point",
    "coordinates": [168.000, -9.133]
    }
    }
    }
    },
    "facets": {
    "propertyTypeFacet": {
    "type": "string",
    "path": "property_type"
    }
    }
    }
    }
map[
count:map[lowerBound:610]
facet:map[
propertyTypeFacet:map[
buckets:[
map[_id:Apartment count:334]
map[_id:House count:168]
map[_id:Townhouse count:29]
map[_id:Guest suite count:20]
map[_id:Condominium count:11]
map[_id:Cabin count:8]
map[_id:Serviced apartment count:7]
map[_id:Villa count:7]
map[_id:Bungalow count:5]
map[_id:Guesthouse count:5]
]
]
]
]
1// establish connection and set namespace
2using MongoDB.Bson;
3using MongoDB.Driver;
4
5var client = new MongoClient("<connection-string>");
6var database = client.GetDatabase("sample_airbnb");
7var collection = database.GetCollection<BsonDocument>("listingsAndReviews");
8
9// define query
10var agg = new BsonDocument("$searchMeta",
11 new BsonDocument("facet",
12 new BsonDocument
13 {
14 ["operator"] = new BsonDocument("geoWithin",
15 new BsonDocument
16 {
17 ["path"] = "address.location",
18 ["box"] = new BsonDocument
19 {
20 ["bottomLeft"] = new BsonDocument
21 {
22 ["type"] = "Point",
23 ["coordinates"] = new BsonArray { 112.467, -55.050 }
24 },
25 ["topRight"] = new BsonDocument
26 {
27 ["type"] = "Point",
28 ["coordinates"] = new BsonArray { 168.000, -9.133 }
29 }
30 }
31 }),
32 ["facets"] = new BsonDocument("propertyTypeFacet",
33 new BsonDocument
34 {
35 ["type"] = "string",
36 ["path"] = "property_type"
37 })
38 }));
39
40// run query and print results
41var cursor = collection.Aggregate<BsonDocument>(
42 new BsonDocument[] { agg }
43);
44foreach (var result in cursor.ToEnumerable())
45{
46 Console.WriteLine(result);
47}
map[
count:map[lowerBound:610]
facet:map[
propertyTypeFacet:map[
buckets:[
map[_id:Apartment count:334]
map[_id:House count:168]
map[_id:Townhouse count:29]
map[_id:Guest suite count:20]
map[_id:Condominium count:11]
map[_id:Cabin count:8]
map[_id:Serviced apartment count:7]
map[_id:Villa count:7]
map[_id:Bungalow count:5]
map[_id:Guesthouse count:5]
]
]
]
]
1// run-geo-box-metadata-query.go
2
3package main
4
5import (
6 "context"
7 "fmt"
8 "log"
9
10 "go.mongodb.org/mongo-driver/bson"
11 "go.mongodb.org/mongo-driver/mongo"
12 "go.mongodb.org/mongo-driver/mongo/options"
13)
14
15func main() {
16 // establish connection and set namespace
17 client, err := mongo.Connect(context.TODO(),
18 options.Client().ApplyURI("<connection-string>"))
19 if err != nil {
20 log.Fatal(err)
21 }
22 defer client.Disconnect(context.TODO())
23
24 collection := client.Database("sample_airbnb").Collection("listingsAndReviews")
25
26 // define query
27 searchStage := bson.D{{"$searchMeta", bson.D{
28 {"facet", bson.D{
29 {"operator", bson.D{
30 {"geoWithin", bson.D{
31 {"path", "address.location"},
32 {"box", bson.D{
33 {"bottomLeft", bson.D{
34 {"type", "Point"},
35 {"coordinates", bson.A{112.467, -55.050}},
36 }},
37 {"topRight", bson.D{
38 {"type", "Point"},
39 {"coordinates", bson.A{168.000, -9.133}},
40 }},
41 }},
42 }},
43 }},
44 {"facets", bson.D{
45 {"propertyTypeFacet", bson.D{
46 {"type", "string"},
47 {"path", "property_type"},
48 }},
49 }},
50 }},
51 }}}
52
53 // run query and print results
54 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage})
55 if err != nil {
56 log.Fatal(err)
57 }
58 defer cursor.Close(context.TODO())
59
60 for cursor.Next(context.TODO()) {
61 var result bson.M
62 if err := cursor.Decode(&result); err != nil {
63 log.Fatal(err)
64 }
65 fmt.Println(result)
66 }
67}
map[
count:map[lowerBound:610]
facet:map[
propertyTypeFacet:map[
buckets:[
map[_id:Apartment count:334]
map[_id:House count:168]
map[_id:Townhouse count:29]
map[_id:Guest suite count:20]
map[_id:Condominium count:11]
map[_id:Cabin count:8]
map[_id:Serviced apartment count:7]
map[_id:Villa count:7]
map[_id:Bungalow count:5]
map[_id:Guesthouse count:5]
]
]
]
]
1import org.bson.Document;
2import com.mongodb.client.MongoClient;
3import com.mongodb.client.MongoClients;
4import com.mongodb.client.MongoCollection;
5import com.mongodb.client.MongoDatabase;
6import java.util.Arrays;
7
8public class GeoBoxMetadataQuery {
9 public static void main(String[] args) {
10 // establish connection and set namespace
11 String uri = "<connection-string>";
12
13 try (MongoClient mongoClient = MongoClients.create(uri)) {
14 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
15 MongoCollection<Document> collection = database.getCollection("listingsAndReviews");
16
17 // define query
18 Document agg = new Document("$searchMeta",
19 new Document("facet",
20 new Document()
21 .append("operator", new Document("geoWithin",
22 new Document()
23 .append("path", "address.location")
24 .append("box", new Document()
25 .append("bottomLeft", new Document()
26 .append("type", "Point")
27 .append("coordinates", Arrays.asList(112.467, -55.050)))
28 .append("topRight", new Document()
29 .append("type", "Point")
30 .append("coordinates", Arrays.asList(168.000, -9.133))))))
31 .append("facets", new Document("propertyTypeFacet",
32 new Document()
33 .append("type", "string")
34 .append("path", "property_type")))));
35
36 // run query and print results
37 collection.aggregate(Arrays.asList(agg))
38 .forEach(doc -> System.out.println(doc.toJson()));
39 }
40 }
41}
map[
count:map[lowerBound:610]
facet:map[
propertyTypeFacet:map[
buckets:[
map[_id:Apartment count:334]
map[_id:House count:168]
map[_id:Townhouse count:29]
map[_id:Guest suite count:20]
map[_id:Condominium count:11]
map[_id:Cabin count:8]
map[_id:Serviced apartment count:7]
map[_id:Villa count:7]
map[_id:Bungalow count:5]
map[_id:Guesthouse count:5]
]
]
]
]
1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("listingsAndReviews")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$searchMeta",
19 Document("facet",
20 Document("operator",
21 Document("geoWithin",
22 Document("path", "address.location")
23 .append("box",
24 Document("bottomLeft",
25 Document("type", "Point")
26 .append("coordinates", listOf(112.467, -55.050)))
27 .append("topRight",
28 Document("type", "Point")
29 .append("coordinates", listOf(168.000, -9.133))))))
30 .append("facets",
31 Document("propertyTypeFacet",
32 Document("type", "string")
33 .append("path", "property_type"))))
34 )
35
36 // run query and print results
37 val resultsFlow = collection.aggregate<Document>(listOf(agg))
38 resultsFlow.collect { println(it) }
39 }
40 mongoClient.close()
41}
Document{
{count=Document{{lowerBound=610}},
facet=Document{
{propertyTypeFacet=Document{
{buckets=[Document{
{_id=Apartment, count=334}
},
Document{
{_id=House, count=168}},
Document{
{_id=Townhouse, count=29}},
Document{
{_id=Guest suite, count=20}
},
Document{
{_id=Condominium, count=11}
},
Document{
{_id=Cabin, count=8}
},
Document{
{_id=Serviced apartment, count=7}
}, Document{
{_id=Villa, count=7}
},
Document{
{_id=Bungalow, count=5}
},
Document{
{_id=Guesthouse, count=5}
}
]
}
}}
}}
}
1// run-geo-box-metadata-query.js
2
3// establish connection and set namespace
4const { MongoClient } = require("mongodb");
5const uri = "<connection-string>";
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_airbnb");
11 const collection = database.collection("listingsAndReviews");
12
13 // define query
14 const agg = [
15 {
16 "$searchMeta": {
17 "facet": {
18 "operator": {
19 "geoWithin": {
20 "path": "address.location",
21 "box": {
22 "bottomLeft": {
23 "type": "Point",
24 "coordinates": [112.467, -55.050]
25 },
26 "topRight": {
27 "type": "Point",
28 "coordinates": [168.000, -9.133]
29 }
30 }
31 }
32 },
33 "facets": {
34 "propertyTypeFacet": {
35 "type": "string",
36 "path": "property_type"
37 }
38 }
39 }
40 }
41 }
42 ];
43
44 // run query and print results
45 const result = collection.aggregate(agg);
46 await result.forEach((doc) => {
47 console.log(JSON.stringify(doc, null, 2));
48 });
49 } finally {
50 await client.close();
51 }
52}
53run().catch(console.dir);
{
"count": {
"lowerBound": 610
},
"facet": {
"propertyTypeFacet": {
"buckets": [
{
"_id": "Apartment",
"count": 334
},
{
"_id": "House",
"count": 168
},
{
"_id": "Townhouse",
"count": 29
},
{
"_id": "Guest suite",
"count": 20
},
{
"_id": "Condominium",
"count": 11
},
{
"_id": "Cabin",
"count": 8
},
{
"_id": "Serviced apartment",
"count": 7
},
{
"_id": "Villa",
"count": 7
},
{
"_id": "Bungalow",
"count": 5
},
{
"_id": "Guesthouse",
"count": 5
}
]
}
}
}
1# run-geo-box-metadata-query.py
2
3# establish connection and set namespace
4import pymongo
5
6client = pymongo.MongoClient("<connection-string>")
7database = client["sample_airbnb"]
8collection = database["listingsAndReviews"]
9
10# define query
11query = [
12 {
13 "$searchMeta": {
14 "facet": {
15 "operator": {
16 "geoWithin": {
17 "path": "address.location",
18 "box": {
19 "bottomLeft": {
20 "type": "Point",
21 "coordinates": [112.467, -55.050]
22 },
23 "topRight": {
24 "type": "Point",
25 "coordinates": [168.000, -9.133]
26 }
27 }
28 }
29 },
30 "facets": {
31 "propertyTypeFacet": {
32 "type": "string",
33 "path": "property_type"
34 }
35 }
36 }
37 }
38 }
39]
40
41# run query and print results
42results = collection.aggregate(query)
43for document in results:
44 print(document)
{'count': {'lowerBound': 610}, 'facet': {'propertyTypeFacet': {'buckets': [{'_id': 'Apartment', 'count': 334}, {'_id': 'House', 'count': 168}, {'_id': 'Townhouse', 'count': 29}, {'_id': 'Guest suite', 'count': 20}, {'_id': 'Condominium', 'count': 11}, {'_id': 'Cabin', 'count': 8}, {'_id': 'Serviced apartment', 'count': 7}, {'_id': 'Villa', 'count': 7}, {'_id': 'Bungalow', 'count': 5}, {'_id': 'Guesthouse', 'count': 5}]}}}

次のクエリでは、 geoWithin演算子とcircleフィールドを使用して、カナダ内の指定された座標の半径 1 マイル以内のプロパティを検索します。

クエリには以下が含まれます。

  • 出力を3の結果に制限する$limitステージ

  • $projectステージでは、 nameaddressを除くすべてのフィールドが除外されます。

注意

MongoDB Search クエリに default という名前のインデックスを指定する必要はありません。インデックスに他の名前がある場合は、indexフィールドを指定する必要があります。


➤ このページの [言語の選択] ドロップダウンメニューを使用して、このセクションの例の言語を設定します。


{
"$search": {
"geoWithin": {
"circle": {
"center": {
"type": "Point",
"coordinates": [-73.54, 45.54]
},
"radius": 1600
},
"path": "address.location"
}
}
}
1SCORE: 1 _id: “10059244
2 access: "Vous avez accès à tout l'appartement."
3 accommodates: 2
4 address: Object
5 street: "Montréal, Québec, Canada"
6 suburb: "Hochelaga-Maisonneuve"
7 government_area: "Mercier-Hochelaga-Maisonneuve"
8 market: "Montreal"
9 country: "Canada"
10 country_code: "CA"
11 location: Object
12 type: "Point"
13 coordinates: Array (2)
14 0: -73.54949
15 1: 45.54548
16 is_location_exact: false
17
18SCORE: 1 _id: “13732894
19 access: "Accès à la chambre, à la salle de bain, à la salle à dîner, à la cuisi…"
20 accommodates: 2
21 address: Object
22 street: "Montréal, QC, Canada"
23 suburb: "Gay Village"
24 government_area: "Ville-Marie"
25 market: "Montreal"
26 country: "Canada"
27 country_code: "CA"
28 location: Object
29 type: "Point"
30 coordinates: Array (2)
31 0: -73.54985
32 1: 45.52797
33 is_location_exact: false
34
35SCORE: 1 _id: “14896503
36 access: "Appartment, you have access to the back balcony and in the shed there …"
37 accommodates: 4
38 address: Object
39 street: "Montréal, Québec, Canada"
40 suburb: "Mercier-Hochelaga-Maisonneuve"
41 government_area: "Mercier-Hochelaga-Maisonneuve"
42 market: "Montreal"
43 country: "Canada"
44 country_code: "CA"
45 location: Object
46 type: "Point"
47 coordinates: Array (2)
48 0: -73.55208
49 1: 45.55157
50 is_location_exact: true
51
52SCORE: 1 _id: “16507273
53 access: "You have all the apartment."
54 accommodates: 4
55 address: Object
56 street: "Montréal, QC, Canada"
57 suburb: "Hochelaga-Maisonneuve"
58 government_area: "Mercier-Hochelaga-Maisonneuve"
59 market: "Montreal"
60 country: "Canada"
61 country_code: "CA"
62 location: Object
63 type: "Point"
64 coordinates: Array (2)
65 0: -73.54141
66 1: 45.5447
67 is_location_exact: false
68
69SCORE: 1 _id: “18139662
70 access: "-Access to: Large private double room Bed sheets, linens, covers, to…"
71 accommodates: 3
72 address: Object
73 street: "Montréal, Québec, Canada"
74 suburb: "Gay Village"
75 government_area: "Ville-Marie"
76 market: "Montreal"
77 country: "Canada"
78 country_code: "CA"
79 location: Object
80 type: "Point"
81 coordinates: Array (2)
82 0: -73.54921
83 1: 45.52811
84 is_location_exact: true
85
86SCORE: 1 _id: “18485581
87 access: "Fully independent apartment with its own entrance and own set of keys.…"
88 accommodates: 4
89 address: Object
90 street: "Montréal, Québec, Canada"
91 suburb: "Le Plateau-Mont-Royal"
92 government_area: "Ville-Marie"
93 market: "Montreal"
94 country: "Canada"
95 country_code: "CA"
96 location: Object
97 type: "Point"
98 coordinates: Array (2)
99 0: -73.55818
100 1: 45.53688
101 is_location_exact: true
102
103SCORE: 1 _id: “19086528
104 access: "Vous aurez accès à toutes les pièces communes de la maison ( Salon, cu…"
105 accommodates: 6
106 address: Object
107 street: "Montréal, Québec, Canada"
108 suburb: "Gay Village"
109 government_area: "Ville-Marie"
110 market: "Montreal"
111 country: "Canada"
112 country_code: "CA"
113 location: Object
114 type: "Point"
115 coordinates: Array (2)
116 0: -73.54923
117 1: 45.52764
118 is_location_exact: true
119
120SCORE: 1 _id: “19296654
121 access: "The whole home will be yours!"
122 accommodates: 6
123 address: Object
124 street: "Montréal, Québec, Canada"
125 suburb: "Mercier-Hochelaga-Maisonneuve"
126 government_area: "Mercier-Hochelaga-Maisonneuve"
127 market: "Montreal"
128 country: "Canada"
129 country_code: "CA"
130 location: Object
131 type: "Point"
132 coordinates: Array (2)
133 0: -73.53516
134 1: 45.54855
135 is_location_exact: true
136
137SCORE: 1 _id: “20254510
138 access: ""
139 accommodates: 2
140 address: Object
141 street: "Montréal, Québec, Canada"
142 suburb: "Mercier-Hochelaga-Maisonneuve"
143 government_area: "Mercier-Hochelaga-Maisonneuve"
144 market: "Montreal"
145 country: "Canada"
146 country_code: "CA"
147 location: Object
148 type: "Point"
149 coordinates: Array (2)
150 0: -73.53971
151 1: 45.54737
152 is_location_exact: true
153
154SCORE: 1 _id: “21248215
155 access: "You have access to the backyard as well as a parking space. Depending …"
156 accommodates: 4
157 address: Object
158 street: "Montréal, Québec, Canada"
159 suburb: "Mercier-Hochelaga-Maisonneuve"
160 government_area: "Ville-Marie"
161 market: "Montreal"
162 country: "Canada"
163 country_code: "CA"
164 location: Object
165 type: "Point"
166 coordinates: Array (2)
167 0: -73.54414
168 1: 45.52984
169 is_location_exact: true
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])
SCORE: 1 _id: “10059244
access: "Vous avez accès à tout l'appartement."
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54949
1: 45.54548
is_location_exact: false
SCORE: 1 _id: “13732894
access: "Accès à la chambre, à la salle de bain, à la salle à dîner, à la cuisi…"
accommodates: 2
address: Object
street: "Montréal, QC, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54985
1: 45.52797
is_location_exact: false
SCORE: 1 _id: “14896503
access: "Appartment, you have access to the back balcony and in the shed there …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55208
1: 45.55157
is_location_exact: true
SCORE: 1 _id: “16507273
access: "You have all the apartment."
accommodates: 4
address: Object
street: "Montréal, QC, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54141
1: 45.5447
is_location_exact: false
SCORE: 1 _id: “18139662
access: "-Access to: Large private double room Bed sheets, linens, covers, to…"
accommodates: 3
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54921
1: 45.52811
is_location_exact: true
SCORE: 1 _id: “18485581
access: "Fully independent apartment with its own entrance and own set of keys.…"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Le Plateau-Mont-Royal"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55818
1: 45.53688
is_location_exact: true
SCORE: 1 _id: “19086528
access: "Vous aurez accès à toutes les pièces communes de la maison ( Salon, cu…"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54923
1: 45.52764
is_location_exact: true
SCORE: 1 _id: “19296654
access: "The whole home will be yours!"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53516
1: 45.54855
is_location_exact: true
SCORE: 1 _id: “20254510
access: ""
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53971
1: 45.54737
is_location_exact: true
SCORE: 1 _id: “21248215
access: "You have access to the backyard as well as a parking space. Depending …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54414
1: 45.52984
is_location_exact: true

MongoDB Compass で次のクエリを実行する方法については、「クエリを定義する」を参照してください。

パイプラインステージ
クエリ

$search

{
"geoWithin": {
"circle": {
"center": {
"type": "Point",
"coordinates": [-73.54, 45.54]
},
"radius": 1600
},
"path": "address.location"
}
}

$limit

3

$project

{
"_id": 0,
"name": 1,
"address": 1
}
SCORE: 1 _id: “10059244
access: "Vous avez accès à tout l'appartement."
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54949
1: 45.54548
is_location_exact: false
SCORE: 1 _id: “13732894
access: "Accès à la chambre, à la salle de bain, à la salle à dîner, à la cuisi…"
accommodates: 2
address: Object
street: "Montréal, QC, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54985
1: 45.52797
is_location_exact: false
SCORE: 1 _id: “14896503
access: "Appartment, you have access to the back balcony and in the shed there …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55208
1: 45.55157
is_location_exact: true
SCORE: 1 _id: “16507273
access: "You have all the apartment."
accommodates: 4
address: Object
street: "Montréal, QC, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54141
1: 45.5447
is_location_exact: false
SCORE: 1 _id: “18139662
access: "-Access to: Large private double room Bed sheets, linens, covers, to…"
accommodates: 3
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54921
1: 45.52811
is_location_exact: true
SCORE: 1 _id: “18485581
access: "Fully independent apartment with its own entrance and own set of keys.…"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Le Plateau-Mont-Royal"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55818
1: 45.53688
is_location_exact: true
SCORE: 1 _id: “19086528
access: "Vous aurez accès à toutes les pièces communes de la maison ( Salon, cu…"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54923
1: 45.52764
is_location_exact: true
SCORE: 1 _id: “19296654
access: "The whole home will be yours!"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53516
1: 45.54855
is_location_exact: true
SCORE: 1 _id: “20254510
access: ""
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53971
1: 45.54737
is_location_exact: true
SCORE: 1 _id: “21248215
access: "You have access to the backyard as well as a parking space. Depending …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54414
1: 45.52984
is_location_exact: true
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.GeoJsonObjectModel;
6using MongoDB.Driver.Search;
7
8public class GeoCircleQuery
9{
10 private const string MongoConnectionString = "<connection-string>";
11
12 public static void Main(string[] args)
13 {
14 // allow automapping of the camelCase database fields to our PropertyDocument
15 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
16 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
17
18 // connect to your Atlas cluster
19 var mongoClient = new MongoClient(MongoConnectionString);
20 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
21 var listingsCollection = airbnbDatabase.GetCollection<PropertyDocument>("listingsAndReviews");
22
23 // define and run pipeline
24 var results = listingsCollection.Aggregate()
25 .Search(Builders<PropertyDocument>.Search.GeoWithin(
26 property => property.Address!.Location,
27 new GeoWithinCircle<GeoJson2DCoordinates>(
28 new GeoJsonPoint<GeoJson2DCoordinates>(new GeoJson2DCoordinates(-73.54, 45.54)),
29 1600
30 )
31 ))
32 .Limit(3)
33 .Project<PropertyDocument>(Builders<PropertyDocument>.Projection
34 .Include(property => property.Name)
35 .Include(property => property.Address)
36 .Exclude(property => property.Id))
37 .ToList();
38
39 // print results
40 foreach (var property in results)
41 {
42 Console.WriteLine(property.ToJson());
43 }
44 }
45}
46
47[BsonIgnoreExtraElements]
48public class PropertyDocument
49{
50 [BsonIgnoreIfDefault]
51 public ObjectId Id { get; set; }
52 public string? Name { get; set; }
53 public AddressDocument? Address { get; set; }
54}
55
56[BsonIgnoreExtraElements]
57public class AddressDocument
58{
59 public GeoJsonPoint<GeoJson2DCoordinates>? Location { get; set; }
60 public string? Street { get; set; }
61 public string? Country { get; set; }
62}
SCORE: 1 _id: “10059244
access: "Vous avez accès à tout l'appartement."
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54949
1: 45.54548
is_location_exact: false
SCORE: 1 _id: “13732894
access: "Accès à la chambre, à la salle de bain, à la salle à dîner, à la cuisi…"
accommodates: 2
address: Object
street: "Montréal, QC, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54985
1: 45.52797
is_location_exact: false
SCORE: 1 _id: “14896503
access: "Appartment, you have access to the back balcony and in the shed there …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55208
1: 45.55157
is_location_exact: true
SCORE: 1 _id: “16507273
access: "You have all the apartment."
accommodates: 4
address: Object
street: "Montréal, QC, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54141
1: 45.5447
is_location_exact: false
SCORE: 1 _id: “18139662
access: "-Access to: Large private double room Bed sheets, linens, covers, to…"
accommodates: 3
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54921
1: 45.52811
is_location_exact: true
SCORE: 1 _id: “18485581
access: "Fully independent apartment with its own entrance and own set of keys.…"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Le Plateau-Mont-Royal"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55818
1: 45.53688
is_location_exact: true
SCORE: 1 _id: “19086528
access: "Vous aurez accès à toutes les pièces communes de la maison ( Salon, cu…"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54923
1: 45.52764
is_location_exact: true
SCORE: 1 _id: “19296654
access: "The whole home will be yours!"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53516
1: 45.54855
is_location_exact: true
SCORE: 1 _id: “20254510
access: ""
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53971
1: 45.54737
is_location_exact: true
SCORE: 1 _id: “21248215
access: "You have access to the backyard as well as a parking space. Depending …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54414
1: 45.52984
is_location_exact: true
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14// define structure of listingsAndReviews collection
15type Property struct {
16 Name string `bson:"name" json:"name"`
17 PropertyType string `bson:"property_type" json:"property_type"`
18 Address struct {
19 Location struct {
20 Type string `bson:"type" json:"type"`
21 Coordinates []float64 `bson:"coordinates" json:"coordinates"`
22 } `bson:"location" json:"location"`
23 Street string `bson:"street" json:"street"`
24 Country string `bson:"country" json:"country"`
25 } `bson:"address" json:"address"`
26 Score float64 `bson:"score" json:"score"`
27}
28
29func main() {
30 var err error
31 // connect to the Atlas cluster
32 ctx := context.Background()
33 client, err := mongo.Connect(options.Client().SetTimeout(5*time.Second).ApplyURI("<connection-string>"))
34 if err != nil {
35 panic(err)
36 }
37 defer client.Disconnect(ctx)
38 // set namespace
39 collection := client.Database("sample_airbnb").Collection("listingsAndReviews")
40 // define pipeline
41 searchStage := bson.D{{Key: "$search", Value: bson.M{
42 "geoWithin": bson.M{
43 "circle": bson.M{
44 "center": bson.M{
45 "type": "Point",
46 "coordinates": []float64{-73.54, 45.54},
47 },
48 "radius": 1600,
49 },
50 "path": "address.location",
51 },
52 }}}
53 limitStage := bson.D{{Key: "$limit", Value: 3}}
54 projectStage := bson.D{{Key: "$project", Value: bson.D{
55 {Key: "_id", Value: 0},
56 {Key: "name", Value: 1},
57 {Key: "address", Value: 1},
58 {Key: "property_type", Value: 1},
59 {Key: "score", Value: bson.D{{Key: "$meta", Value: "searchScore"}}},
60 }}}
61 // run pipeline
62 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
63 if err != nil {
64 panic(err)
65 }
66 // print results
67 var results []Property
68 if err = cursor.All(context.TODO(), &results); err != nil {
69 panic(err)
70 }
71
72 // Convert results to JSON and print
73 jsonResults, err := json.MarshalIndent(results, "", " ")
74 if err != nil {
75 panic(err)
76 }
77 fmt.Println(string(jsonResults))
78}
[
{
"name": "Ligne verte - à 15 min de métro du centre ville.",
"property_type": "Apartment",
"address": {
"location": {
"type": "Point",
"coordinates": [
-73.54949,
45.54548
]
},
"street": "Montréal, Québec, Canada",
"country": "Canada"
},
"score": 1
},
{
"name": "Belle chambre à côté Metro Papineau",
"property_type": "Apartment",
"address": {
"location": {
"type": "Point",
"coordinates": [
-73.54985,
45.52797
]
},
"street": "Montréal, QC, Canada",
"country": "Canada"
},
"score": 1
},
{
"name": "L'IDÉAL, ( à 2 min du métro Pie-IX ).",
"property_type": "Apartment",
"address": {
"location": {
"type": "Point",
"coordinates": [
-73.55208,
45.55157
]
},
"street": "Montréal, Québec, Canada",
"country": "Canada"
},
"score": 1
}
]
1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.excludeId;
5import static com.mongodb.client.model.Projections.fields;
6import static com.mongodb.client.model.Projections.include;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class GeoCircleQuery {
14 public static void main( String[] args ) {
15
16 // define query
17 Document agg = new Document("$search",
18 new Document("geoWithin",
19 new Document("circle",
20 new Document("center",
21 new Document("type", "Point")
22 .append("coordinates", Arrays.asList(-73.54, 45.54)))
23 .append("radius", 1600))
24 .append("path", "address.location")));
25
26 // specify connection
27 String uri = "<connection-string>";
28
29 // establish connection and set namespace
30 try (MongoClient mongoClient = MongoClients.create(uri)) {
31 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
32 MongoCollection<Document> collection = database.getCollection("listingsAndReviews");
33 // run query and print results
34 collection.aggregate(Arrays.asList(agg,
35 limit(3),
36 project(fields(excludeId(), include("name", "address")))))
37 .forEach(doc -> System.out.println(doc.toJson()));
38 }
39 }
40}
SCORE: 1 _id:10059244
access: "Vous avez accès à tout l'appartement."
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54949
1: 45.54548
is_location_exact: false
SCORE: 1 _id:13732894
access: "Accès à la chambre, à la salle de bain, à la salle à dîner, à la cuisi…"
accommodates: 2
address: Object
street: "Montréal, QC, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54985
1: 45.52797
is_location_exact: false
SCORE: 1 _id:14896503
access: "Appartment, you have access to the back balcony and in the shed there …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55208
1: 45.55157
is_location_exact: true
SCORE: 1 _id:16507273
access: "You have all the apartment."
accommodates: 4
address: Object
street: "Montréal, QC, Canada"
suburb: "Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54141
1: 45.5447
is_location_exact: false
SCORE: 1 _id:18139662
access: "-Access to: Large private double room Bed sheets, linens, covers, to…"
accommodates: 3
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54921
1: 45.52811
is_location_exact: true
SCORE: 1 _id:18485581
access: "Fully independent apartment with its own entrance and own set of keys.…"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Le Plateau-Mont-Royal"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.55818
1: 45.53688
is_location_exact: true
SCORE: 1 _id:19086528
access: "Vous aurez accès à toutes les pièces communes de la maison ( Salon, cu…"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Gay Village"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54923
1: 45.52764
is_location_exact: true
SCORE: 1 _id:19296654
access: "The whole home will be yours!"
accommodates: 6
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53516
1: 45.54855
is_location_exact: true
SCORE: 1 _id:20254510
access: ""
accommodates: 2
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Mercier-Hochelaga-Maisonneuve"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.53971
1: 45.54737
is_location_exact: true
SCORE: 1 _id:21248215
access: "You have access to the backyard as well as a parking space. Depending …"
accommodates: 4
address: Object
street: "Montréal, Québec, Canada"
suburb: "Mercier-Hochelaga-Maisonneuve"
government_area: "Ville-Marie"
market: "Montreal"
country: "Canada"
country_code: "CA"
location: Object
type: "Point"
coordinates: Array (2)
0: -73.54414
1: 45.52984
is_location_exact: true
1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("listingsAndReviews")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("geoWithin",
20 Document("circle",
21 Document("center",
22 Document("type", "Point")
23 .append("coordinates", listOf(-73.54, 45.54)))
24 .append("radius", 1600))
25 .append("path", "address.location"))
26 )
27
28 // run query and print results
29 val resultsFlow = collection.aggregate<Document>(
30 listOf(
31 agg,
32 limit(3),
33 project(fields(excludeId(), include("name", "address")))
34 )
35 )
36 resultsFlow.collect { println(it) }
37 }
38 mongoClient.close()
39}
Document{{name=Ligne verte - à 15 min de métro du centre ville., address=Document{{street=Montréal, Québec, Canada, suburb=Hochelaga-Maisonneuve, government_area=Mercier-Hochelaga-Maisonneuve, market=Montreal, country=Canada, country_code=CA, location=Document{{type=Point, coordinates=[-73.54949, 45.54548], is_location_exact=false}}}}}}
Document{{name=Belle chambre à côté Metro Papineau, address=Document{{street=Montréal, QC, Canada, suburb=Gay Village, government_area=Ville-Marie, market=Montreal, country=Canada, country_code=CA, location=Document{{type=Point, coordinates=[-73.54985, 45.52797], is_location_exact=false}}}}}}
Document{{name=L'IDÉAL, ( à 2 min du métro Pie-IX )., address=Document{{street=Montréal, Québec, Canada, suburb=Mercier-Hochelaga-Maisonneuve, government_area=Mercier-Hochelaga-Maisonneuve, market=Montreal, country=Canada, country_code=CA, location=Document{{type=Point, coordinates=[-73.55208, 45.55157], is_location_exact=true}}}}}}
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 'geoWithin': {
21 'circle': {
22 'center': {
23 'type': 'Point',
24 'coordinates': [-73.54, 45.54]
25 },
26 'radius': 1600
27 },
28 'path': 'address.location'
29 }
30 }
31 }, {
32 '$limit': 3
33 }, {
34 '$project': {
35 '_id': 0,
36 'name': 1,
37 'address': 1
38 }
39 }
40 ];
41
42 // run pipeline
43 const result = coll.aggregate(agg);
44
45 // print results
46 await result.forEach((doc) => console.log(doc));
47 } finally {
48 await client.close();
49 }
50}
51run().catch(console.dir);
{
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: [Array], 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: [Array], 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: [Array], is_location_exact: true }
}
}
1import pymongo
2import dns.resolver
3
4# connect to your Atlas cluster
5client = pymongo.MongoClient("<connection-string>")
6
7# define pipeline
8pipeline = [
9 {
10 "$search": {
11 "geoWithin": {
12 "circle": {
13 "center": {
14 "type": "Point",
15 "coordinates": [-73.54, 45.54]
16 },
17 "radius": 1600
18 },
19 "path": "address.location"
20 }
21 }
22 },
23 {
24 "$limit": 3
25 },
26 {
27 "$project": {
28 "_id": 0,
29 "name": 1,
30 "address": 1
31 }
32 }
33]
34
35# run pipeline
36result = client.sample_airbnb.listingsAndReviews.aggregate(pipeline)
37
38# print results
39for i in result:
40 print(i)
{'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}}}

次の例では、 geoWithin演算子とgeometryフィールドを使用して、クラウドのプロパティを検索しています。 typeフィールドは、領域が GeoJSON 多角形であるか、マルチポリゴンであるかを指定します。

クエリには、次のものが含まれます。

  • $limitステージを使用して、出力を3の結果に制限します。

  • $projectステージでは、 nameaddressを除くすべてのフィールドが除外されます。

注意

MongoDB Search クエリに default という名前のインデックスを指定する必要はありません。インデックスに他の名前がある場合は、indexフィールドを指定する必要があります。


➤ このページの [言語の選択] ドロップダウンメニューを使用して、このセクションの例の言語を設定します。


次のMongoDB Search クエリは、

  • 複合$searchステージを使用して次の操作を行います。

    • 結果mustcoordinatesのセットで定義されたPolygon内にあることを指定します。

    • タイプcondominiumのプロパティの結果を優先します。

  • $projectステージを使用して次の操作を行います。

    • すべてのフィールドを除外しますnameaddressproperty_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: 1 _id: “1001265
2 access: "Pool, hot tub and tennis"
3 accommodates: 2
4 address: Object
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: Object
12 type: "Point"
13 coordinates: Array (2)
14 0: -157.83919
15 1: 21.28634
16 is_location_exact: true
17
18SCORE: 1 _id: “1022200
19 access: ""
20 accommodates: 6
21 address: Object
22 street: "Kailua-Kona, HI, United States"
23 suburb: "Kailua/Kona"
24 government_area: "North Kona"
25 market: "The Big Island"
26 country: "United States"
27 country_code: "US"
28 location: Object
29 type: "Point"
30 coordinates: Array (2)
31 0: -155.96445
32 1: 19.5702
33 is_location_exact: true
34
35SCORE: 1 _id: “10227000
36 access: ""
37 accommodates: 4
38 address: Object
39 street: "Lahaina, HI, United States"
40 suburb: "Maui"
41 government_area: "Lahaina"
42 market: "Maui"
43 country: "United States"
44 country_code: "US"
45 location: Object
46 type: "Point"
47 coordinates: Array (2)
48 0: -156.68012
49 1: 20.96996
50 is_location_exact: true
51
52SCORE: 1 _id: “10266175
53 access: "Full access - Must go through 24 hour Security Gate - Lockstate door c…"
54 accommodates: 4
55 address: Object
56 street: "Waianae, HI, United States"
57 suburb: "Leeward Side"
58 government_area: "Waianae"
59 market: "Oahu"
60 country: "United States"
61 country_code: "US"
62 location: Object
63 type: "Point"
64 coordinates: Array (2)
65 0: -158.20291
66 1: 21.4818
67 is_location_exact: true
68
69SCORE: 1 _id: “10280433
70 access: ""
71 accommodates: 2
72 address: Object
73 street: "Volcano, HI, United States"
74 suburb: "Island of Hawaiʻi"
75 government_area: "Puna"
76 market: "The Big Island"
77 country: "United States"
78 country_code: "US"
79 location: Object
80 type: "Point"
81 coordinates: Array (2)
82 0: -155.21763
83 1: 19.42151
84 is_location_exact: false
85
86SCORE: 1 _id: “10317142
87 access: ""
88 accommodates: 14
89 address: Object
90 street: "Laie, HI, United States"
91 suburb: "Ko'olauloa"
92 government_area: "Koolauloa"
93 market: "Oahu"
94 country: "United States"
95 country_code: "US"
96 location: Object
97 type: "Point"
98 coordinates: Array (2)
99 0: -157.91952
100 1: 21.63549
101 is_location_exact: true
102
103SCORE: 1 _id: “10392282
104 access: "Private driveway to access the property, parking on site."
105 accommodates: 2
106 address: Object
107 street: "Waialua, HI, United States"
108 suburb: "Oʻahu"
109 government_area: "North Shore Oahu"
110 market: "Oahu"
111 country: "United States"
112 country_code: "US"
113 location: Object
114 type: "Point"
115 coordinates: Array (2)
116 0: -158.1602
117 1: 21.57561
118 is_location_exact: false
119
120SCORE: 1 _id: “1042446
121 access: ""
122 accommodates: 4
123 address: Object
124 street: "Kihei, HI, United States"
125 suburb: "Maui"
126 government_area: "Kihei-Makena"
127 market: "Maui"
128 country: "United States"
129 country_code: "US"
130 location: Object
131 type: "Point"
132 coordinates: Array (2)
133 0: -156.46881
134 1: 20.78621
135 is_location_exact: true
136
137SCORE: 1 _id: “10527243
138 access: ""
139 accommodates: 4
140 address: Object
141 street: "Hilo, HI, United States"
142 suburb: "Island of Hawaiʻi"
143 government_area: "South Hilo"
144 market: "The Big Island"
145 country: "United States"
146 country_code: "US"
147 location: Object
148 type: "Point"
149 coordinates: Array (2)
150 0: -155.09259
151 1: 19.73108
152 is_location_exact: true
153
154SCORE: 1 _id: “10548991
155 access: "You will have access to the entire home, which can be split into two s…"
156 accommodates: 11
157 address: Object
158 street: "Kailua-Kona, HI, United States"
159 suburb: "Island of Hawaiʻi"
160 government_area: "North Kona"
161 market: "The Big Island"
162 country: "United States"
163 country_code: "US"
164 location: Object
165 type: "Point"
166 coordinates: Array (2)
167 0: -155.97349
168 1: 19.61318
169 is_location_exact: false
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 で次のクエリを実行する方法については、「クエリを定義する」を参照してください。

パイプラインステージ
クエリ

$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
}
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 .Limit (10)
43 .Project<AirbnbDocument>(Builders<AirbnbDocument>.Projection
44 .Include(airbnb => airbnb.PropertyType)
45 .Include(airbnb => airbnb.Address!.Location)
46 .Include(airbnb => airbnb.Name)
47 .Exclude(airbnb => airbnb.Id)
48 .MetaSearchScore(airbnb => airbnb.Score))
49 .ToList();
50
51 // print results
52 foreach (var x in results) {
53 Console.WriteLine(x.ToJson());
54 }
55 }
56}
57[BsonIgnoreExtraElements]
58public class AirbnbDocument
59{
60 [BsonIgnoreIfDefault]
61 public ObjectId Id { get; set; }
62 public string? Name { get; set; }
63 [BsonElement("property_type")]
64 public string? PropertyType { get; set; }
65 public Address? Address { get; set; }
66 public double Score { get; set; }
67}
68[BsonIgnoreExtraElements]
69public class Address
70{
71 public GeoJsonPoint<GeoJson2DCoordinates>? Location { get; set; }
72}
{
"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.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.computed;
5import static com.mongodb.client.model.Projections.excludeId;
6import static com.mongodb.client.model.Projections.fields;
7import static com.mongodb.client.model.Projections.include;
8import com.mongodb.client.MongoClient;
9import com.mongodb.client.MongoClients;
10import com.mongodb.client.MongoCollection;
11import com.mongodb.client.MongoDatabase;
12import org.bson.Document;
13
14public class GeoPolygonQuery {
15 public static void main( String[] args ) {
16 Document agg = new Document( "$search",
17 new Document( "index", "<INDEX-NAME>")
18 .append("compound",
19 new Document("must", Arrays.asList(new Document("geoWithin",
20 new Document("geometry",
21 new Document("type", "Polygon")
22 .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)))))
23 .append("path", "address.location"))))
24 .append("should", Arrays.asList(new Document("text",
25 new Document("path", "property_type")
26 .append("query", "Condominium"))))));
27
28 String uri = "<connection-string>";
29
30 try (MongoClient mongoClient = MongoClients.create(uri)) {
31 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
32 MongoCollection<Document> collection = database.getCollection("listingsAndReviews");
33
34 collection.aggregate(Arrays.asList(agg,
35 limit(10),
36 project(fields(excludeId(), include("name", "address", "property_type"), computed("score", new Document("$meta", "searchScore"))))))
37 .forEach(doc -> System.out.println(doc.toJson() + "\n"));
38 }
39 }
40}
{"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}

次のコード例では、次を行います。

  • mongodb パッケージと依存関係をインポートします。

  • クラスターへの接続を確立します。

  • クエリに一致するドキュメントを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クラスのインスタンスを作成します。

  • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

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);
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
name: '~Ao Lele~ Flying Cloud',
property_type: 'Treehouse',
address: {
street: 'Volcano, HI, United States',
suburb: 'Island of Hawaiʻi',
government_area: 'Puna',
market: 'The Big Island',
country: 'United States',
country_code: 'US',
location: { type: 'Point', coordinates: [Array], is_location_exact: false }
},
score: 1
}
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
name: 'Banyan Bungalow',
property_type: 'Bungalow',
address: {
street: 'Waialua, HI, United States',
suburb: 'Oʻahu',
government_area: 'North Shore Oahu',
market: 'Oahu',
country: 'United States',
country_code: 'US',
location: { type: 'Point', coordinates: [Array], is_location_exact: false }
},
score: 1
}
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
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: [Array], is_location_exact: true }
},
score: 1
}
{
name: 'Jubilee By The Sea (Ocean Views)',
property_type: 'House',
address: {
street: 'Kailua-Kona, HI, United States',
suburb: 'Island of Hawaiʻi',
government_area: 'North Kona',
market: 'The Big Island',
country: 'United States',
country_code: 'US',
location: { type: 'Point', coordinates: [Array], is_location_exact: false }
},
score: 1
}

次のコード例では、次を行います。

  • pymongo、 MongoDBのPythonドライバー、および DNSシードリスト接続文字列を使用して pymongoAtlas に接続するために必要な dns モジュールをインポートします。

  • クラスターへの接続を確立するための MongoClientクラスのインスタンスを作成します。

    • 複合$searchステージを使用して次の操作を行います。

      • 結果mustcoordinatesのセットで定義されたPolygon内にあることを指定します。

      • タイプcondominiumのプロパティの結果を優先します。

    • $projectステージを使用して次の操作を行います。

      • すべてのフィールドを除外しますnameaddressproperty_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)
{'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': 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ʻi', '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ʻahu', '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ʻ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': 1.0}
{'name': 'Jubilee By The Sea (Ocean Views)', 'property_type': 'House', 'address': {'street': 'Kailua-Kona, HI, United States', 'suburb': 'Island of Hawaiʻi', '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}

➤ このページの [言語の選択] ドロップダウンメニューを使用して、このセクションの例の言語を設定します。


次のMongoDB Search クエリでは、geoWithin 演算子と geometryフィールドを使用して、クラウドのプロパティを検索します。typeフィールドは、領域が GeoJSON 多角形であるか、マルチポリゴンであるかを指定します。

クエリには以下が含まれます。

  • $limitステージを使用して、出力を3の結果に制限します。

  • $projectステージでは、 nameaddressを除くすべてのフィールドが除外されます。

注意

MongoDB Search クエリに default という名前のインデックスを指定する必要はありません。インデックスに他の名前がある場合は、indexフィールドを指定する必要があります。

{
"$search": {
"geoWithin": {
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[[[-157.8412413882,21.2882235819],
[-157.8607925468,21.2962046205],
[-157.8646640634,21.3077019651],
[-157.862776699,21.320776283],
[-157.8341758705,21.3133826738],
[-157.8349985678,21.3000822569],
[-157.8412413882,21.2882235819]]],
[[[-157.852898124,21.301208833],
[-157.8580050499,21.3050871833],
[-157.8587346108,21.3098050385],
[-157.8508811028,21.3119240258],
[-157.8454308541,21.30396767],
[-157.852898124,21.301208833]]]
]
},
"path": "address.location"
}
}
}
1SCORE: 1 _id: “12906431
2 access: "Porch with a love seat, table and three chairs. Regular trash is a gra…"
3 accommodates: 4
4 address: Object
5 street: "Honolulu, HI, United States"
6 suburb: "Makiki/Lower Punchbowl/Tantalus"
7 government_area: "Primary Urban Center"
8 market: "Oahu"
9 country: "United States"
10 country_code: "US"
11 location: Object
12 type: "Point"
13 coordinates: Array (2)
14 0: -157.84343
15 1: 21.30852
16 is_location_exact: false
17
18SCORE: 1 _id: “15808180
19 access: "We used key-less lock, you can check in anytime after 3pm. You can enj…"
20 accommodates: 3
21 address: Object
22 street: "Honolulu, HI, United States"
23 suburb: "Oʻahu"
24 government_area: "Primary Urban Center"
25 market: "Oahu"
26 country: "United States"
27 country_code: "US"
28 location: Object
29 type: "Point"
30 coordinates: Array (2)
31 0: -157.85228
32 1: 21.31184
33 is_location_exact: true
34
35SCORE: 1 _id: “17663877
36 access: ""
37 accommodates: 1
38 address: Object
39 street: "Honolulu, HI, United States"
40 suburb: "Oʻahu"
41 government_area: "Primary Urban Center"
42 market: "Oahu"
43 country: "United States"
44 country_code: "US"
45 location: Object
46 type: "Point"
47 coordinates: Array (2)
48 0: -157.83889
49 1: 21.29776
50 is_location_exact: false
51
52SCORE: 1 _id: “22148252
53 access: "Access your unit 24 hours a day. \"Great location, save on the resort a…\""
54 accommodates: 6
55 address: Object
56 street: "Honolulu, HI, United States"
57 suburb: "Honolulu"
58 government_area: "Primary Urban Center"
59 market: "Oahu"
60 country: "United States"
61 country_code: "US"
62 location: Object
63 type: "Point"
64 coordinates: Array (2)
65 0: -157.86021
66 1: 21.30823
67 is_location_exact: true
68
69SCORE: 1 _id: “2530337
70 access: "Our family home is upstairs, and we share the entrance gate, but you'l…"
71 accommodates: 2
72 address: Object
73 street: "Honolulu, HI, United States"
74 suburb: "Honolulu"
75 government_area: "Primary Urban Center"
76 market: "Oahu"
77 country: "United States"
78 country_code: "US"
79 location: Object
80 type: "Point"
81 coordinates: Array (2)
82 0: -157.85041
83 1: 21.31008
84 is_location_exact: true
85
86SCORE: 1 _id: “7650220
87 access: "You'll have access to the entire apartment, including the kitchen, the…"
88 accommodates: 6
89 address: Object
90 street: "Honolulu, HI, United States"
91 suburb: "Ala Moana/Kakaako"
92 government_area: "Primary Urban Center"
93 market: "Oahu"
94 country: "United States"
95 country_code: "US"
96 location: Object
97 type: "Point"
98 coordinates: Array (2)
99 0: -157.85062
100 1: 21.30094
101 is_location_exact: true
db.listingsAndReviews.aggregate([
{
"$search": {
"geoWithin": {
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[[[-157.8412413882,21.2882235819],
[-157.8607925468,21.2962046205],
[-157.8646640634,21.3077019651],
[-157.862776699,21.320776283],
[-157.8341758705,21.3133826738],
[-157.8349985678,21.3000822569],
[-157.8412413882,21.2882235819]]],
[[[-157.852898124,21.301208833],
[-157.8580050499,21.3050871833],
[-157.8587346108,21.3098050385],
[-157.8508811028,21.3119240258],
[-157.8454308541,21.30396767],
[-157.852898124,21.301208833]]]
]
},
"path": "address.location"
}
}
},
{
"$limit": 3
},
{
"$project": {
"_id": 0,
"name": 1,
"address": 1
}
}
])
SCORE: 1 _id: “12906431
access: "Porch with a love seat, table and three chairs. Regular trash is a gra…"
accommodates: 4
address: Object
street: "Honolulu, HI, United States"
suburb: "Makiki/Lower Punchbowl/Tantalus"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.84343
1: 21.30852
is_location_exact: false
SCORE: 1 _id: “15808180
access: "We used key-less lock, you can check in anytime after 3pm. You can enj…"
accommodates: 3
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85228
1: 21.31184
is_location_exact: true
SCORE: 1 _id: “17663877
access: ""
accommodates: 1
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.83889
1: 21.29776
is_location_exact: false
SCORE: 1 _id: “22148252
access: "Access your unit 24 hours a day. \"Great location, save on the resort a…\""
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.86021
1: 21.30823
is_location_exact: true
SCORE: 1 _id: “2530337
access: "Our family home is upstairs, and we share the entrance gate, but you'l…"
accommodates: 2
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85041
1: 21.31008
is_location_exact: true
SCORE: 1 _id: “7650220
access: "You'll have access to the entire apartment, including the kitchen, the…"
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Ala Moana/Kakaako"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85062
1: 21.30094
is_location_exact: true

MongoDB Compass で次のクエリを実行する方法については、「クエリを定義する」を参照してください。

パイプラインステージ
クエリ

$search

{
"geoWithin": {
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[[[-157.8412413882,21.2882235819],
[-157.8607925468,21.2962046205],
[-157.8646640634,21.3077019651],
[-157.862776699,21.320776283],
[-157.8341758705,21.3133826738],
[-157.8349985678,21.3000822569],
[-157.8412413882,21.2882235819]]],
[[[-157.852898124,21.301208833],
[-157.8580050499,21.3050871833],
[-157.8587346108,21.3098050385],
[-157.8508811028,21.3119240258],
[-157.8454308541,21.30396767],
[-157.852898124,21.301208833]]]
]
},
"path": "address.location"
}
}

$limit

3

$project

{
"_id": 0,
"name": 1,
"address": 1
}
SCORE: 1 _id: “12906431
access: "Porch with a love seat, table and three chairs. Regular trash is a gra…"
accommodates: 4
address: Object
street: "Honolulu, HI, United States"
suburb: "Makiki/Lower Punchbowl/Tantalus"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.84343
1: 21.30852
is_location_exact: false
SCORE: 1 _id: “15808180
access: "We used key-less lock, you can check in anytime after 3pm. You can enj…"
accommodates: 3
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85228
1: 21.31184
is_location_exact: true
SCORE: 1 _id: “17663877
access: ""
accommodates: 1
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.83889
1: 21.29776
is_location_exact: false
SCORE: 1 _id: “22148252
access: "Access your unit 24 hours a day. \"Great location, save on the resort a…\""
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.86021
1: 21.30823
is_location_exact: true
SCORE: 1 _id: “2530337
access: "Our family home is upstairs, and we share the entrance gate, but you'l…"
accommodates: 2
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85041
1: 21.31008
is_location_exact: true
SCORE: 1 _id: “7650220
access: "You'll have access to the entire apartment, including the kitchen, the…"
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Ala Moana/Kakaako"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85062
1: 21.30094
is_location_exact: true
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.GeoJsonObjectModel;
6using MongoDB.Driver.Search;
7
8public class GeoMultiPolygonQuery
9{
10 private const string MongoConnectionString = "<connection-string>";
11
12 public static void Main(string[] args)
13 {
14 // allow automapping of the camelCase database fields to our PropertyDocument
15 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
16 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
17
18 // connect to your Atlas cluster
19 var mongoClient = new MongoClient(MongoConnectionString);
20 var airbnbDatabase = mongoClient.GetDatabase("sample_airbnb");
21 var listingsCollection = airbnbDatabase.GetCollection<PropertyDocument>("listingsAndReviews");
22
23 // define multi-polygon geometry
24 var multiPolygon = new GeoJsonMultiPolygon<GeoJson2DCoordinates>(
25 new GeoJsonMultiPolygonCoordinates<GeoJson2DCoordinates>(
26 new GeoJsonPolygonCoordinates<GeoJson2DCoordinates>[]
27 {
28 new GeoJsonPolygonCoordinates<GeoJson2DCoordinates>(
29 new GeoJsonLinearRingCoordinates<GeoJson2DCoordinates>(
30 new GeoJson2DCoordinates[]
31 {
32 new GeoJson2DCoordinates(-157.8412413882, 21.2882235819),
33 new GeoJson2DCoordinates(-157.8607925468, 21.2962046205),
34 new GeoJson2DCoordinates(-157.8646640634, 21.3077019651),
35 new GeoJson2DCoordinates(-157.862776699, 21.320776283),
36 new GeoJson2DCoordinates(-157.8341758705, 21.3133826738),
37 new GeoJson2DCoordinates(-157.8349985678, 21.3000822569),
38 new GeoJson2DCoordinates(-157.8412413882, 21.2882235819)
39 })),
40 new GeoJsonPolygonCoordinates<GeoJson2DCoordinates>(
41 new GeoJsonLinearRingCoordinates<GeoJson2DCoordinates>(
42 new GeoJson2DCoordinates[]
43 {
44 new GeoJson2DCoordinates(-157.852898124, 21.301208833),
45 new GeoJson2DCoordinates(-157.8580050499, 21.3050871833),
46 new GeoJson2DCoordinates(-157.8587346108, 21.3098050385),
47 new GeoJson2DCoordinates(-157.8508811028, 21.3119240258),
48 new GeoJson2DCoordinates(-157.8454308541, 21.30396767),
49 new GeoJson2DCoordinates(-157.852898124, 21.301208833)
50 }))
51 }));
52
53 // define and run pipeline
54 var results = listingsCollection.Aggregate()
55 .Search(Builders<PropertyDocument>.Search.GeoWithin(
56 property => property.Address!.Location,
57 multiPolygon
58 ))
59 .Limit(3)
60 .Project<PropertyDocument>(Builders<PropertyDocument>.Projection
61 .Include(property => property.Name)
62 .Include(property => property.Address)
63 .Exclude(property => property.Id))
64 .ToList();
65
66 // print results
67 foreach (var property in results)
68 {
69 Console.WriteLine(property.ToJson());
70 }
71 }
72}
73
74[BsonIgnoreExtraElements]
75public class PropertyDocument
76{
77 [BsonIgnoreIfDefault]
78 public ObjectId Id { get; set; }
79 public string? Name { get; set; }
80 public AddressDocument? Address { get; set; }
81}
82
83[BsonIgnoreExtraElements]
84public class AddressDocument
85{
86 public GeoJsonPoint<GeoJson2DCoordinates>? Location { get; set; }
87 public string? Street { get; set; }
88 public string? Country { get; set; }
89}
SCORE: 1 _id: “12906431
access: "Porch with a love seat, table and three chairs. Regular trash is a gra…"
accommodates: 4
address: Object
street: "Honolulu, HI, United States"
suburb: "Makiki/Lower Punchbowl/Tantalus"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.84343
1: 21.30852
is_location_exact: false
SCORE: 1 _id: “15808180
access: "We used key-less lock, you can check in anytime after 3pm. You can enj…"
accommodates: 3
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85228
1: 21.31184
is_location_exact: true
SCORE: 1 _id: “17663877
access: ""
accommodates: 1
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.83889
1: 21.29776
is_location_exact: false
SCORE: 1 _id: “22148252
access: "Access your unit 24 hours a day. \"Great location, save on the resort a…\""
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.86021
1: 21.30823
is_location_exact: true
SCORE: 1 _id: “2530337
access: "Our family home is upstairs, and we share the entrance gate, but you'l…"
accommodates: 2
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85041
1: 21.31008
is_location_exact: true
SCORE: 1 _id: “7650220
access: "You'll have access to the entire apartment, including the kitchen, the…"
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Ala Moana/Kakaako"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85062
1: 21.30094
is_location_exact: true
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14// define structure of listingsAndReviews collection
15type Property struct {
16 Name string `bson:"name" json:"name"`
17 Address struct {
18 Location struct {
19 Type string `bson:"type" json:"type"`
20 Coordinates []float64 `bson:"coordinates" json:"coordinates"`
21 } `bson:"location" json:"location"`
22 Street string `bson:"street" json:"street"`
23 Country string `bson:"country" json:"country"`
24 } `bson:"address" json:"address"`
25}
26
27func main() {
28 var err error
29 // connect to the Atlas cluster
30 ctx := context.Background()
31 client, err := mongo.Connect(options.Client().SetTimeout(5*time.Second).ApplyURI("<connection-string>"))
32 if err != nil {
33 panic(err)
34 }
35 defer client.Disconnect(ctx)
36 // set namespace
37 collection := client.Database("sample_airbnb").Collection("listingsAndReviews")
38 // define pipeline
39 searchStage := bson.D{{Key: "$search", Value: bson.M{
40 "geoWithin": bson.M{
41 "geometry": bson.M{
42 "type": "MultiPolygon",
43 "coordinates": []interface{}{
44 []interface{}{
45 []interface{}{
46 []float64{-157.8412413882, 21.2882235819},
47 []float64{-157.8607925468, 21.2962046205},
48 []float64{-157.8646640634, 21.3077019651},
49 []float64{-157.862776699, 21.320776283},
50 []float64{-157.8341758705, 21.3133826738},
51 []float64{-157.8349985678, 21.3000822569},
52 []float64{-157.8412413882, 21.2882235819},
53 },
54 },
55 []interface{}{
56 []interface{}{
57 []float64{-157.852898124, 21.301208833},
58 []float64{-157.8580050499, 21.3050871833},
59 []float64{-157.8587346108, 21.3098050385},
60 []float64{-157.8508811028, 21.3119240258},
61 []float64{-157.8454308541, 21.30396767},
62 []float64{-157.852898124, 21.301208833},
63 },
64 },
65 },
66 },
67 "path": "address.location",
68 },
69 }}}
70 limitStage := bson.D{{Key: "$limit", Value: 3}}
71 projectStage := bson.D{{Key: "$project", Value: bson.D{{Key: "_id", Value: 0}, {Key: "name", Value: 1}, {Key: "address", Value: 1}}}}
72 // run pipeline
73 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage})
74 if err != nil {
75 panic(err)
76 }
77 // print results
78 var results []Property
79 if err = cursor.All(context.TODO(), &results); err != nil {
80 panic(err)
81 }
82
83 // Convert results to JSON and print
84 jsonResults, err := json.MarshalIndent(results, "", " ")
85 if err != nil {
86 panic(err)
87 }
88 fmt.Println(string(jsonResults))
89}
[
{
"name": "Heart of Honolulu, 2BD gem! Free Garage Parking!",
"address": {
"location": {
"type": "Point",
"coordinates": [
-157.84343,
21.30852
]
},
"street": "Honolulu, HI, United States",
"country": "United States"
}
},
{
"name": "Private Studio closed to town w/ compact parking",
"address": {
"location": {
"type": "Point",
"coordinates": [
-157.85228,
21.31184
]
},
"street": "Honolulu, HI, United States",
"country": "United States"
}
},
{
"name": "Comfortable Room (2) at Affordable Rates",
"address": {
"location": {
"type": "Point",
"coordinates": [
-157.83889,
21.29776
]
},
"street": "Honolulu, HI, United States",
"country": "United States"
}
}
]
1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.excludeId;
5import static com.mongodb.client.model.Projections.fields;
6import static com.mongodb.client.model.Projections.include;
7import com.mongodb.client.MongoClient;
8import com.mongodb.client.MongoClients;
9import com.mongodb.client.MongoCollection;
10import com.mongodb.client.MongoDatabase;
11import org.bson.Document;
12
13public class GeoMultiPolygonQuery {
14 public static void main( String[] args ) {
15
16 // define query
17 Document agg = new Document("$search",
18 new Document("geoWithin",
19 new Document("geometry",
20 new Document("type", "MultiPolygon")
21 .append("coordinates", Arrays.asList(
22 Arrays.asList(
23 Arrays.asList(
24 Arrays.asList(-157.8412413882, 21.2882235819),
25 Arrays.asList(-157.8607925468, 21.2962046205),
26 Arrays.asList(-157.8646640634, 21.3077019651),
27 Arrays.asList(-157.862776699, 21.320776283),
28 Arrays.asList(-157.8341758705, 21.3133826738),
29 Arrays.asList(-157.8349985678, 21.3000822569),
30 Arrays.asList(-157.8412413882, 21.2882235819)
31 )
32 ),
33 Arrays.asList(
34 Arrays.asList(
35 Arrays.asList(-157.852898124, 21.301208833),
36 Arrays.asList(-157.8580050499, 21.3050871833),
37 Arrays.asList(-157.8587346108, 21.3098050385),
38 Arrays.asList(-157.8508811028, 21.3119240258),
39 Arrays.asList(-157.8454308541, 21.30396767),
40 Arrays.asList(-157.852898124, 21.301208833)
41 )
42 )
43 )))
44 .append("path", "address.location")));
45
46 // specify connection
47 String uri = "<connection-string>";
48
49 // establish connection and set namespace
50 try (MongoClient mongoClient = MongoClients.create(uri)) {
51 MongoDatabase database = mongoClient.getDatabase("sample_airbnb");
52 MongoCollection<Document> collection = database.getCollection("listingsAndReviews");
53 // run query and print results
54 collection.aggregate(Arrays.asList(agg,
55 limit(3),
56 project(fields(excludeId(), include("name", "address")))))
57 .forEach(doc -> System.out.println(doc.toJson()));
58 }
59 }
60}
SCORE: 1 _id:12906431
access: "Porch with a love seat, table and three chairs. Regular trash is a gra…"
accommodates: 4
address: Object
street: "Honolulu, HI, United States"
suburb: "Makiki/Lower Punchbowl/Tantalus"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.84343
1: 21.30852
is_location_exact: false
SCORE: 1 _id:15808180
access: "We used key-less lock, you can check in anytime after 3pm. You can enj…"
accommodates: 3
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85228
1: 21.31184
is_location_exact: true
SCORE: 1 _id:17663877
access: ""
accommodates: 1
address: Object
street: "Honolulu, HI, United States"
suburb: "Oʻahu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.83889
1: 21.29776
is_location_exact: false
SCORE: 1 _id:22148252
access: "Access your unit 24 hours a day. \"Great location, save on the resort a…\""
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.86021
1: 21.30823
is_location_exact: true
SCORE: 1 _id:2530337
access: "Our family home is upstairs, and we share the entrance gate, but you'l…"
accommodates: 2
address: Object
street: "Honolulu, HI, United States"
suburb: "Honolulu"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85041
1: 21.31008
is_location_exact: true
SCORE: 1 _id:7650220
access: "You'll have access to the entire apartment, including the kitchen, the…"
accommodates: 6
address: Object
street: "Honolulu, HI, United States"
suburb: "Ala Moana/Kakaako"
government_area: "Primary Urban Center"
market: "Oahu"
country: "United States"
country_code: "US"
location: Object
type: "Point"
coordinates: Array (2)
0: -157.85062
1: 21.30094
is_location_exact: true
1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_airbnb")
13 val collection = database.getCollection<Document>("listingsAndReviews")
14
15 runBlocking {
16 // define query
17 val agg = Document(
18 "\$search",
19 Document("geoWithin",
20 Document("geometry",
21 Document("type", "MultiPolygon")
22 .append("coordinates", listOf(
23 listOf(
24 listOf(
25 listOf(-157.8412413882, 21.2882235819),
26 listOf(-157.8607925468, 21.2962046205),
27 listOf(-157.8646640634, 21.3077019651),
28 listOf(-157.862776699, 21.320776283),
29 listOf(-157.8341758705, 21.3133826738),
30 listOf(-157.8349985678, 21.3000822569),
31 listOf(-157.8412413882, 21.2882235819)
32 )
33 ),
34 listOf(
35 listOf(
36 listOf(-157.852898124, 21.301208833),
37 listOf(-157.8580050499, 21.3050871833),
38 listOf(-157.8587346108, 21.3098050385),
39 listOf(-157.8508811028, 21.3119240258),
40 listOf(-157.8454308541, 21.30396767),
41 listOf(-157.852898124, 21.301208833)
42 )
43 )
44 )))
45 .append("path", "address.location"))
46 )
47
48 // run query and print results
49 val resultsFlow = collection.aggregate<Document>(
50 listOf(
51 agg,
52 limit(3),
53 project(fields(excludeId(), include("name", "address")))
54 )
55 )
56 resultsFlow.collect { println(it) }
57 }
58 mongoClient.close()
59}
Document{{name=Heart of Honolulu, 2BD gem! Free Garage Parking!, address=Document{{street=Honolulu, HI, United States, suburb=Makiki/Lower Punchbowl/Tantalus, government_area=Primary Urban Center, market=Oahu, country=United States, country_code=US, location=Document{{type=Point, coordinates=[-157.84343, 21.30852], is_location_exact=false}}}}}}
Document{{name=Private Studio closed to town w/ compact parking, 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.85228, 21.31184], is_location_exact=true}}}}}}
Document{{name=Comfortable Room (2) at Affordable Rates, 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.83889, 21.29776], is_location_exact=false}}}}}}
1// run-geo-multipolygon-query.js
2
3// establish connection and set namespace
4const { MongoClient } = require("mongodb");
5const uri = "<connection-string>";
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_airbnb");
11 const collection = database.collection("listingsAndReviews");
12
13 // define query
14 const agg = [
15 {
16 "$search": {
17 "geoWithin": {
18 "geometry": {
19 "type": "MultiPolygon",
20 "coordinates": [
21 [
22 [
23 [-157.8412413882, 21.2882235819],
24 [-157.8607925468, 21.2962046205],
25 [-157.8646640634, 21.3077019651],
26 [-157.862776699, 21.320776283],
27 [-157.8341758705, 21.3133826738],
28 [-157.8349985678, 21.3000822569],
29 [-157.8412413882, 21.2882235819]
30 ]
31 ],
32 [
33 [
34 [-157.852898124, 21.301208833],
35 [-157.8580050499, 21.3050871833],
36 [-157.8587346108, 21.3098050385],
37 [-157.8508811028, 21.3119240258],
38 [-157.8454308541, 21.30396767],
39 [-157.852898124, 21.301208833]
40 ]
41 ]
42 ]
43 },
44 "path": "address.location"
45 }
46 }
47 },
48 {
49 "$limit": 3
50 },
51 {
52 "$project": {
53 "_id": 0,
54 "name": 1,
55 "address": 1
56 }
57 }
58 ];
59
60 // run query and print results
61 const result = collection.aggregate(agg);
62 await result.forEach((doc) => console.log(doc));
63 } finally {
64 await client.close();
65 }
66}
67run().catch(console.dir);
{
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: [Array], 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: [Array], 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: [Array], is_location_exact: false }
}
}
1# run-geo-multipolygon-query.py
2
3# establish connection and set namespace
4import pymongo
5
6client = pymongo.MongoClient("<connection-string>")
7database = client["sample_airbnb"]
8collection = database["listingsAndReviews"]
9
10# define query
11query = [
12 {
13 "$search": {
14 "geoWithin": {
15 "geometry": {
16 "type": "MultiPolygon",
17 "coordinates": [
18 [
19 [
20 [-157.8412413882, 21.2882235819],
21 [-157.8607925468, 21.2962046205],
22 [-157.8646640634, 21.3077019651],
23 [-157.862776699, 21.320776283],
24 [-157.8341758705, 21.3133826738],
25 [-157.8349985678, 21.3000822569],
26 [-157.8412413882, 21.2882235819]
27 ]
28 ],
29 [
30 [
31 [-157.852898124, 21.301208833],
32 [-157.8580050499, 21.3050871833],
33 [-157.8587346108, 21.3098050385],
34 [-157.8508811028, 21.3119240258],
35 [-157.8454308541, 21.30396767],
36 [-157.852898124, 21.301208833]
37 ]
38 ]
39 ]
40 },
41 "path": "address.location"
42 }
43 }
44 },
45 {
46 "$limit": 3
47 },
48 {
49 "$project": {
50 "_id": 0,
51 "name": 1,
52 "address": 1
53 }
54 }
55]
56
57# run query and print results
58results = collection.aggregate(query)
59for document in results:
60 print(document)
{'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

項目一覧