该 $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 区域或跨越国际日期线,则结果可能不准确或不可预知。
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。