您好,我有以下问题:我想使用 $geoNear (计算两点之间的距离),但在 $loopback 之后(以及我加入的集合)。这是 companyBases 集合的模型(我想加入它):
{
"_id" : ObjectId("5d7cfe13f42e7345d967b378"),
"location" : {
"type" : "Point",
"coordinates" : [
20.633856,
49.761268
]
},
"vehicles" : [
{
"_id" : ObjectId("5d7cfe13f42e7345d967b340"),
...other fields that doesn't matter
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是车辆集合:
{
"_id" : ObjectId("5d7cfe13f42e7345d967b340"),
...other fields that doesn't matter
}
Run Code Online (Sandbox Code Playgroud)
我想加入 companyBase 集合来聚合车辆集合:
db.vehicles.aggregate([
{
$lookup: {
from: "companybases",
let: {
vehicleId: "$_id"
},
pipeline: [
{
$match: {
$expr: { $in: ["$$vehicleId", "$vehicles._id"] }
}
}
],
as: "companyBases"
}
},
{
$unwind: "$companyBases"
},
{
$geoNear: {
near: {
type: "Point",
coordinates: [50.02485, 20.0008]
},
distanceField: "distance",
spherical: true
}
}
]);
Run Code Online (Sandbox Code Playgroud)
但它返回给我:
{
"message" : "$geoNear is only valid as the first stage in a pipeline.",
"operationTime" : "Timestamp(1568472833, 1)",
"ok" : 0,
"code" : 40602,
"codeName" : "Location40602",
"$clusterTime" : {
"clusterTime" : "Timestamp(1568472833, 1)",
"signature" : {
"hash" : "AAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"keyId" : "0"
}
},
"name" : "MongoError"
}
Run Code Online (Sandbox Code Playgroud)
当我在 companybases 集合上执行相同的管道时,它会返回带有计算距离的文档:
db.companybases.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [50.02485, 20.0008]
},
distanceField: "distance",
spherical: true
}
}
]);
Run Code Online (Sandbox Code Playgroud)
结果:
{
"_id" : ObjectId("5d7cfe13f42e7345d967b378"),
"location" : {
"type" : "Point",
"coordinates" : [
20.633856,
49.761268
]
},
"vehicles" : [
{
...some fields
},
],
...some fields
"distance" : 4209673.447019393
}
Run Code Online (Sandbox Code Playgroud)
我意识到该错误可能是因为缺少车辆集合索引。那么有什么方法可以用 $lookup 来计算 $geoNear 的距离吗?或者也许这是不可能的,我必须自己做?
简单的解决方案(您可以将 $geoNear 放入 $lookup 管道中):
db.vehicles.aggregate([
{
$lookup: {
from: "companybases",
let: {
vehicleId: "$_id"
},
pipeline: [
{
$geoNear: {
near: {
type: "Point",
coordinates: [50.02485, 20.0008]
},
distanceField: "distance",
spherical: true
}
},
{
$match: {
$expr: { $in: ["$$vehicleId", "$vehicles._id"] }
}
}
],
as: "companyBases"
}
},
{
$unwind: "$companyBases"
}
]);
Run Code Online (Sandbox Code Playgroud)
但这给性能留下了深刻的印象(至少需要 5 秒),因为 $geoNear 在匹配之前使用。
归档时间: |
|
查看次数: |
1533 次 |
最近记录: |