$centerSphere 運算子會使用球面幾何來為 $geoWithin 查詢指定一個圓形區域。 此運算子適用於需要考慮地球球形的地理計算。
語法
{
$geoWithin: {
$centerSphere: [ [ <x>, <y> ], <radius in radians> ]
}
}
參數
| 參數 | Description |
|---|---|
<x> |
圓形中心點的經度 |
<y> |
圓形中心點的緯度 |
<radius in radians> |
球體的半徑 (以弧度為單位) (將距離 (公里) 除以 6371,即可轉換為弧度) |
範例
請參考商店集合中的此範例檔。
{
"_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 公里 (半徑 ≈ 0.157 弧度) 內尋找兩家商店。 該查詢可以幫助識別附近的商店以進行區域營銷活動或供應鏈優化。
// 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)
此查詢傳回的前兩個結果是:
[
{
"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"
}
]
這很重要
$centerSphere 運算子會使用球面幾何來計算距離,這讓它在進行地球上的距離計算時,比 $center 更精確。
半徑必須以弧度為單位指定。
座標應依下列順序指定:[經度, 緯度]。
如果地理緩衝區超出 UTM 區域範圍,或跨越國際換日線,則結果可能會不準確或無法預測。