Node.js 猫鼬的分类和区别

Node.js 猫鼬的分类和区别,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我的猫鼬查询是: Spread.find(findCase).where('loc').near({ center: { type: 'Point', coordinates: [self.lon, self.lat] }, maxDistance: distance }).sort({ts : -1}).distinct("postId").exec(); 所以我得到了一个错误: Error: s

我的猫鼬查询是:

Spread.find(findCase).where('loc').near({
        center: {
            type: 'Point',
            coordinates: [self.lon, self.lat]
        },
        maxDistance: distance
}).sort({ts : -1}).distinct("postId").exec();
所以我得到了一个错误:

Error: sort cannot be used with distinct
但是如果我用控制台传递查询

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

那么为什么mongoose不允许我在一个查询中选择distinct和sort,我该如何做呢?

从中,
sort
不能与
distinct
一起使用

不能与distinct()一起使用

但您可以执行聚合操作:

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.
}
)
注意:集合上的
loc
字段上需要存在
2dsphere
索引。要创建索引,请参阅:。

测试数据:

db.createCollection("test");

db.test.insert({
    loc : {type: 'Point', coordinates : [42,42]},
    ts : new Date(2014,2,5),
    postId : 1
});

db.test.insert({
    loc : {type: 'Point', coordinates : [42,42]},
    ts : new Date(2014,2,5),
    postId : 1
});

db.test.insert({
    loc : {type: 'Point', coordinates : [42,42]},
    ts : new Date(2014,2,4),
    postId : 2
});

db.test.insert({
    loc : {type: 'Point', coordinates : [42,42]},
    ts : new Date(2014,2,3),
    postId : 3
});
带着疑问

db.test.aggregate([
{
    $geoNear: {
    near : { type: 'Point', coordinates: [ 42, 42 ] },
    distanceField : 'dist.calculated',
    maxDistance: 200,
    spherical: true
    }
},
{
    $sort : {ts: -1}
},
{$group:{"_id":"$postId"}}
]);
给出错误的结果

{ "_id" : 3 }
{ "_id" : 2 }
{ "_id" : 1 }

所以我猜mongo首先应用了分组,然后不能按缺席字段排序。出于这个原因,mongoose可能禁止将distinct与排序一起使用。

您能告诉我们mongoose实际要执行的是什么吗?只需启用调试标志
mongoose.set('debug',true)
。调试模式已设置。在记录完整查询之前,mongoose/node_modules/mquery/lib/mquery.js:2405中抛出了错误。最终,它无法正常工作,下面我发布了一个测试用例。您无法在单个组中对记录进行排序。您提供的代码不正确。排序应该在
$group
之前,
$group
只是为了在记录排序后获取不同的值。很抱歉回答得太晚,您的意思是替换组并在聚合数组中排序?我做了,结果还是错的。或者也许我不明白一些事情,这并不能回答问题,应该是对你原来帖子的更新。请仅将问题的完整答案作为答案发布。