node.jsmongodbmongoose

Sort and distinct in mongoose


My mongoose query is:

Spread.find(findCase).where('loc').near({
        center: {
            type: 'Point',
            coordinates: [self.lon, self.lat]
        },
        maxDistance: distance
}).sort({ts : -1}).distinct("postId").exec();

So I get the error:

Error: sort cannot be used with distinct

But if I pass the query with console

db.spreads.distinct({}).sort({ts: -1});

That is ok.

So why mongoose doesn't let me to select distinct and sort in one query and how can I do it?


Solution

  • From the docs, sort cannot be used with distinct.

    Cannot be used with distinct()

    But you can perform an aggregation operation:

    Spread.aggregate(
    {$geoNear:{
      "near":{"type":"Point","coordinates":[self.lon, self.lat]},
      "distanceField":"dist.calculated",
      "maxDistance":distance,
      "query":findcase,
      "spherical": true
    }},
    {$sort:{"ts":-1}},
    {$group:{"_id":"$postId"}},function(err,resp){
      console.log(resp);
      // handle response.
    }
    )
    

    Note: A 2dsphere Index needs to exist on the collection over the loc field. To create an Index, refer: Does applying a 2dsphere index on a mongoose schema force the location field to be required?.