mongodb, sorting by geoNear and date?

后端 未结 2 1871
Happy的楠姐
Happy的楠姐 2021-01-27 08:23

how to sort by proximity and date in mongoDB? I tried this. But they just sort by date:

   coll.find({\'date\':{$gte:date},\'location\':{$nearSphere:[lat,lng]}})         


        
相关标签:
2条回答
  • 2021-01-27 08:37

    There's no direct way to use $near or $nearSphere and sort by another field, because both of these operators already sort the results of doing a find(). When you sort again by 'date', you're re-sorting the results. What you can do, however, is grab results from the $nearSphere incrementally, and sort each set of results. For example:

    function sortByDate(a, b) { return a.date - b.date; }
    
    // how many results to grab at a time
    var itersize = 10;
    // this will hold your final, two-way sorted results
    var sorted_results = new Array();
    for (var i=0, last=db.coll.count(); i<last-itersize; i+=itersize) {
        var results = db.coll.find( {"date":{$gte:date},
                                     // longitude, then latitude
                                     "location":[lng, lat]} ).skip(i).limit(itersize).toArray();
        // do date sorting app-side for each group of nearSphere-sorted results
        sorted_results = sorted_results.concat( results.sort(sortByDate) );
    }
    

    You should also be aware of the order you specify geospatial coordinates in mongodb queries. MongoDB uses the geojson spec, which does coordinates in X, Y, Z order (i.e., longitude, latitude).

    0 讨论(0)
  • 2021-01-27 08:50

    It's recommended to use $geoNear in an aggregate : https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/

    You can sort on your date and distance in the aggregate :

        coll.aggregate([
       {
         $geoNear: {
            near: { type: "Point", coordinates: [ lat, lng ] },
            key: "location",
            spherical: true,
            distanceField: "dist.calculated",
            query: { "date": {"$gte": date} }
         }
       },
       {$sort: {"dist.calculated":1, "date": 1}}
    ])
    
    0 讨论(0)
提交回复
热议问题