如何在mongodb中按索引值排序数组

时间:2014-02-20 06:11:57

标签: arrays mongodb sorting

嗨我有一些问题,我想要实现的是对索引1中的进度进行排序 我怎么能用mongodb做到这一点?我尝试了一些代码但无法实现它

{ "fb_id" : "user1", "progress" : [  1, 20 ] }
{ "fb_id" : "user2", "progress" : [  2, 10 ] }
{ "fb_id" : "user3", "progress" : [  3 ] }

我预期的结果是某种类似的

{ "fb_id" : "user2", "progress" : [  10 ] }
{ "fb_id" : "user1", "progress" : [  20 ] }

我可以通过一些基本的mongodb查询实现它吗? 谢谢

1 个答案:

答案 0 :(得分:0)

可能更完整:

db.collection.find(
    { "progress.1": {$exists: true} },
    { _id:0, fb_id: 1, progress: {$slice: [-1, 1]}}
).sort({"progress.1": 1})

因此,匹配,投影和排序到您想要的结果。关键在于位置符号。