W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
聚合階段。將記錄按照離給定點(diǎn)從近到遠(yuǎn)輸出。
屬性 | 類型 | 默認(rèn)值 | 必填 | 說明 |
---|---|---|---|---|
near | GeoPoint | 是 | GeoJSON Point,用于判斷距離的點(diǎn) | |
spherical | true | 是 | 必填,值為 true | |
limit | number | 否 | 限制返回記錄數(shù) | |
maxDistance | number | 否 | 距離最大值 | |
minDistance | number | 否 | 距離最小值 | |
query | Object | 否 | 要求記錄必須同時(shí)滿足該條件(語法同 where) | |
distanceMultiplier | number | 否 | 返回時(shí)在距離上乘以該數(shù)字 | |
distanceField | string | 是 | 存放距離的輸出字段名,可以用點(diǎn)表示法表示一個(gè)嵌套字段 | |
includeLocs | string | 否 | 列出要用于距離計(jì)算的字段,如果記錄中有多個(gè)字段都是地理位置時(shí)有用 | |
key | string | 否 | 選擇要用的地理位置索引。如果集合由多個(gè)地理位置索引,則必須指定一個(gè),指定的方式是指定對應(yīng)的字段 |
假設(shè)集合 attractions 有如下記錄:
{
"_id": "geoNear.0",
"city": "Guangzhou",
"docType": "geoNear",
"location": {
"type": "Point",
"coordinates": [
113.30593,
23.1361155
]
},
"name": "Canton Tower"
},
{
"_id": "geoNear.1",
"city": "Guangzhou",
"docType": "geoNear",
"location": {
"type": "Point",
"coordinates": [
113.306789,
23.1564721
]
},
"name": "Baiyun Mountain"
},
{
"_id": "geoNear.2",
"city": "Beijing",
"docType": "geoNear",
"location": {
"type": "Point",
"coordinates": [
116.3949659,
39.9163447
]
},
"name": "The Palace Museum"
},
{
"_id": "geoNear.3",
"city": "Beijing",
"docType": "geoNear",
"location": {
"type": "Point",
"coordinates": [
116.2328567,
40.242373
]
},
"name": "Great Wall"
}
const $ = db.command.aggregate
db.collection('attractions').aggregate()
.geoNear({
distanceField: 'distance', // 輸出的每個(gè)記錄中 distance 即是與給定點(diǎn)的距離
spherical: true,
near: db.Geo.Point(113.3089506, 23.0968251),
query: {
docType: 'geoNear',
},
key: 'location', // 若只有 location 一個(gè)地理位置索引的字段,則不需填
includeLocs: 'location', // 若只有 location 一個(gè)是地理位置,則不需填
})
.end()
返回結(jié)果如下:
{
"_id": "geoNear.0",
"location": {
"type": "Point",
"coordinates": [
113.30593,
23.1361155
]
},
"docType": "geoNear",
"name": "Canton Tower",
"city": "Guangzhou",
"distance": 4384.68131486958
},
{
"_id": "geoNear.1",
"city": "Guangzhou",
"location": {
"type": "Point",
"coordinates": [
113.306789,
23.1564721
]
},
"docType": "geoNear",
"name": "Baiyun Mountain",
"distance": 6643.521654040738
},
{
"_id": "geoNear.2",
"docType": "geoNear",
"name": "The Palace Museum",
"city": "Beijing",
"location": {
"coordinates": [
116.3949659,
39.9163447
],
"type": "Point"
},
"distance": 1894750.4414538583
},
{
"_id": "geoNear.3",
"docType": "geoNear",
"name": "Great Wall",
"city": "Beijing",
"location": {
"type": "Point",
"coordinates": [
116.2328567,
40.242373
]
},
"distance": 1928300.3308822548
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: