2015-01-15 109 views
2

我的貓鼬查詢:排序和貓鼬不同

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}); 

也就是說好。

那麼,爲什麼貓鼬不讓我選擇不同的和排序在一個查詢中,我該怎麼做呢?

+1

你能告訴我們什麼貓鼬實際上試圖執行?只需啓用調試標誌'mongoose.set('debug',true)'。 – Pio 2015-01-15 18:11:08

+0

調試模式已設置。在記錄完整查詢之前,錯誤將引發mongoose/node_modules/mquery/lib/mquery.js:2405 – 2015-01-15 19:46:12

回答

3

docs,sort不能與distinct一起使用。

Cannot be used with 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?

+0

最後它無法正常工作,下面我發佈了一個測試用例 – 2015-02-06 16:52:38

0

測試數據:

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 } 

,所以我猜蒙戈首先應用於分組,然後不能排序缺席現場。出於這個原因,可能貓鼬禁止使用不同的排序。

+1

您無法在單個組中排序記錄。你提出的是不正確的。排序應該在'$ group'之前,'$ group'只是在記錄排序後抓取不同的值。 – BatScream 2015-02-07 01:27:24

+0

對於遲到的答案很抱歉,你的意思是替換組和排序在聚合數組?我做到了,結果仍然是錯誤的。或maby我不明白 – 2015-03-25 16:41:14

+0

我編輯了測試用例 – 2015-03-25 16:47:03