mongodb, sorting by geoNear and date?

后端 未结 2 1883
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条回答
  •  猫巷女王i
    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}}
    ])
    

提交回复
热议问题