简体   繁体   中英

Sort subdocument using mongoose (MongoDB)

I am trying to do something very simple but an new to MongoDB! I have a document called Device and a sub-document called Movement. I want to get the last two movement sub-documents out of Device ordered by last_seen (a date). Here is what I have along with the error I am getting:

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

The Error:

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

You can use 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM