过滤$ geoNear(目标)并根据$ geoNear(origin)进行排序

时间:2018-09-02 08:58:11

标签: mongodb mongoose geospatial geojson geonear

我想显示给定距离内的骑手位置,并根据起点对它们进行排序。

这是数据的样子

searchController.hidesNavigationBarDuringPresentation = false

}

这是我到目前为止完成的作业。

{ 
"_id" : ObjectId("5b5a9cd706f9b02068ebc4a6"), 
"name" : "Bangalore to hyderabad",
"locations" : [
    {
        "coordinates" : [
            77.5945627, 
            12.9715987
        ], 
        "_id" : ObjectId("5b5a9cd706f9b02068ebc4a8"), 
        "formattedAddress" : "Bengaluru, Karnataka, India", 
        "name" : "Bengaluru", 
        "type" : "Point", 
        "googlePlaceId" : "5b0d9fd719c9616d747b8a0d", 
        "placeType" : "origin" //***Sort by this***
    }, 
    {
        "coordinates" : [
            78.486671, 
            17.385044
        ], 
        "_id" : ObjectId("5b5a9cd706f9b02068ebc4a7"), 
        "formattedAddress" : "Hyderabad, Telangana, India", 
        "name" : "Hyderabad", 
        "type" : "Point", 
        "googlePlaceId" : "5b0d9fd719c9616d747b8a0d", 
        "locType" : "destination" // *****Filter by this***
    }
], 

此查询根据所有位置点过滤数据,而与locType无关。

2dsphere是location.coordinates的索引

return await Ride.aggregate([
    {
        $geoNear: {
            near: { type: "Point", coordinates: [ 77.5946,12.8716 ] },
            distanceField: "distance",
            maxDistance: 20000000, //200Kms
            query: { private: false },
            spherical: true
        }
    },
    // { "$sort": { "distance": 1 } },
    { "$skip": 0 },
    { "$limit": 30 }
]);

}

1 个答案:

答案 0 :(得分:1)

我用另一种方法解决了这个问题。

首先,我将距离字段添加到我的数据中。将起点和终点作为单独的对象而不是数组。

{ 
"_id" : ObjectId("5b5a9cd706f9b02068ebc4a6"), 
"name" : "Bangalore to hyderabad",
"origin" : {
        "coordinates" : [
            77.5945627, 
            12.9715987
        ], 
        "_id" : ObjectId("5b5a9cd706f9b02068ebc4a8"), 
        "formattedAddress" : "Bengaluru, Karnataka, India", 
        "name" : "Bengaluru", 
        "type" : "Point", 
        "googlePlaceId" : "5b0d9fd719c9616d747b8a0d", 
    }, 
destination: {
        "coordinates" : [
            78.486671, 
            17.385044
        ], 
        "_id" : ObjectId("5b5a9cd706f9b02068ebc4a7"), 
        "formattedAddress" : "Hyderabad, Telangana, India", 
        "name" : "Hyderabad", 
        "type" : "Point", 
        "googlePlaceId" : "5b0d9fd719c9616d747b8a0d", 
    }

然后我进行查询以在半径为1KM的原点字段上触发geoNear,并查询距离小于200KM的距离。

Ride.aggregate([
    {
        $geoNear: {
            near: { type: "Point", coordinates: [ 77.5946,12.8716 ] },
            distanceField: "distanceFromOrigin",
            maxDistance: 1000, //1Km
            query: { private: false, distance:{$lt:200}},
            spherical: true
        }
    },
    // { "$sort": { "distanceFromOrigin":1,"distance": 1 } },
    { "$skip": 0 },
    { "$limit": 30 }
]);