$centerSphere演算子は、$geoWithin クエリに球面ジオメトリを使用して円を指定します。 この演算子は、地球の球形を考慮する必要がある地理的計算に役立ちます。
構文
{
$geoWithin: {
$centerSphere: [ [ <x>, <y> ], <radius in radians> ]
}
}
パラメーター
| パラメーター | Description |
|---|---|
<x> |
円の中心点の経度 |
<y> |
円の中心点の緯度 |
<radius in radians> |
ラジアン単位の球の半径 (距離をキロメートル単位で 6371 で除算してラジアンに変換する) |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
例 1: 円形領域内の店舗を検索する (地球の球形の計算)
このクエリ例では、Wide World Importers Headphone Corner ストアの場所の約 1,000 km (半径 ≈ 0.157 ラジアン) 内の 2 つのストアを検索します。 このクエリは、地域のマーケティング キャンペーンやサプライ チェーンの最適化のために近くの店舗を特定するのに役立ちます。
// Convert 1000km to radians: 1000/6371 ≈ 0.157
db.stores.find(
{
location: {
$geoWithin: {
$centerSphere: [[-82.5543, -65.105], 0.157]
}
}
},
{
_id: 0,
name: 1,
location: 1,
city: 1
}
).limit(2)
このクエリによって返される最初の 2 つの結果は次のとおりです。
[
{
"name": "Fourth Coffee | Electronics Bazaar - O'Keefeburgh",
"location": { "lat": -64.5856, "lon": -115.5241 },
"city": "O'Keefeburgh"
},
{
"name": "Boulder Innovations | Footwear Outlet - West Sybleberg",
"location": { "lat": -72.73, "lon": -60.2306 },
"city": "West Sybleberg"
}
]
Important
$centerSphere演算子は、球形状を使用して距離を計算し、$centerよりも地球ベースの計算の精度を高めます。
半径はラジアンで指定する必要があります。
座標は、[経度、緯度] の順序で指定する必要があります。
地理的バッファーが UTM ゾーンを超えている場合、または国際日付線を越えた場合、結果が不正確または予測できない可能性があります。