使用mongoose(MongoDB)对子文档进行排序

时间:2016-10-19 22:42:37

标签: node.js mongodb express mongoose

我正在尝试做一些非常简单但是MongoDB的新功能!我有一个名为Device的文档和一个名为Movement的子文档。我希望从last_seen(日期)排序的设备中获取最后两个移动子文档。以下是我所得到的错误:

Device.findOne({device_id: "1234"}, {movements: { $sort: {last_seen: -1}, $slice: 2 }}, function(err, device){
     ...
});

错误:

MongoError: >1 field in obj: { $sort: { last_seen: -1 }, $slice: 2 }

1 个答案:

答案 0 :(得分:0)

您可以使用aggregate

Device.aggregate(
    { $match: { device_id: "1234"}}, // query documents (can return more than one element)
    { $unwind: '$movements'}, //deconstruct the documents
    { $sort: { '$movements.last_seen': -1}},
    { $limit: 2 },
    { $group: { _id: '$device_id', movements: { $push: '$movements }}} //reconstruct the documents
function(err, devices){ 
    //returns an array, probably with one elements depending on `$match` query
});