【问题标题】:Sort and distinct in mongoose在猫鼬中排序和区分
【发布时间】:2015-03-26 00:46:12
【问题描述】:

我的猫鼬查询是:

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 不允许我在一个查询中选择不同的和排序,我该怎么做呢?

【问题讨论】:

  • 你能告诉我们猫鼬实际上试图执行什么吗?只需启用调试标志mongoose.set('debug', true)
  • 已设置调试模式。在记录完整查询之前,会在 mongoose/node_modules/mquery/lib/mquery.js:2405 中引发错误

标签: node.js mongodb mongoose


【解决方案1】:

docs开始,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.
}
)

注意2dsphere 索引需要存在于集合中的 loc 字段上。要创建索引,请参阅:Does applying a 2dsphere index on a mongoose schema force the location field to be required?

【讨论】:

  • 终于不行了,下面我贴了一个测试用例
【解决方案2】:

测试数据:

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 进行排序。

【讨论】:

  • 您无法对单个组中的记录进行排序。您提供的代码不正确。排序应该在$group 之前,$group 只是为了在记录排序后获取不同的值。
  • 抱歉回答迟了,您的意思是替换组并在聚合数组中排序?我做到了,结果仍然是错误的。或者可能我什么都不懂
  • 这不能回答问题,应该是对您原始帖子的更新。请仅发布问题的完整解决方案作为答案。
猜你喜欢
  • 2020-11-21
  • 2015-10-08
  • 2019-09-16
  • 2011-05-17
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
相关资源
最近更新 更多