1

我有照片收藏,我必须在相册中显示当前照片位置。排序条件很复杂: sort({add:1,weight:1,_id:1}) 所以没有机会检查当前之前的照片数量。

我尝试使用 MapReduce,但与 PostgreSQL(44 毫秒)相比,它的工作速度非常慢(615 毫秒)。

在 Mongo 中获取某些元素的行号的最佳做法是什么?

4

1 回答 1

0

这是一个类似分页的问题。本质上,您应该在客户端执行计数。如果你想有一个稳定的顺序,你也应该按_id字段排序(因为它是不可变的)。显然,你已经在这样做了。

[pseudocode]
var criteria = { "album_id" : "foo", ... }; 
var skip = 50; // assuming we're on page 2 and each page has 50 photos 
var cursor = db.Photo.find(criteria).
       sort({"added" :1, "weight" : 1, "_id" : 1}).
       skip(skip).limit(50);
// count() doesn't honour skip or limit, so this is total number of 
// Photos matching 'criteria'
var count = cursor.count(); 

for(var i = 0; i < cursor.length; ++i)
    cursor[i].index = skip + i;
// each photo is now cursor[x].index of 'count' photos total

希望有帮助

于 2013-03-26T13:19:13.503 回答