使用 geoNear 時,將忽略所有沒有位置的行(不是 2dsphere 索引的一部分)。
如何使用 geoNear 獲得最近的結果,但也顯示其他沒有位置的行?沒有位置的行應該在結果中排??名較低。
.collection('users')
.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [userLocArray[0], userLocArray[1]]},
distanceField: "dist.calculated",
spherical: true,
//maxDistance: matchDistance,
}
},
示例檔案(在下面的示例中,用戶xyz和mmm被省略,geoNear因為他們沒有位置欄位。我只是希望它們排名最低,但不能完全省略。
db={
users: [
{
_id: "abc",
name: "abc",
group: 1,
location: {
type: "Point",
coordinates: [
53.23,
67.12
]
},
calculatedDist: 112
},
{
_id: "xyz",
name: "xyyy",
group: 1,
calculatedDist: 13
},
{
_id: "123",
name: "yyy",
group: 1,
location: {
type: "Point",
coordinates: [
54.23,
67.12
]
},
calculatedDist: 13
},
{
_id: "rrr",
name: "tttt",
group: 1,
location: {
type: "Point",
coordinates: [
51.23,
64.12
]
},
calculatedDist: 14
},
{
_id: "mmm",
name: "mmmm",
group: 1,
calculatedDist: 14
},
]
}
uj5u.com熱心網友回復:
您可以簡單地$match在管道末尾添加另一個階段來選擇那些沒有位置的檔案
db.users.aggregate([
{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [
53.23,
67.12
]
},
"distanceField": "d"
}
},
{
"$unionWith": {
"coll": "users",
"pipeline": [
{
"$match": {
"location": null
}
}
]
}
}
])
是的,你是對的,Mongo Playground 無法展示 2d 球體索引行為。但我還是把它放在這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529760.html
標籤:mongodb
