简体   繁体   English

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

[英]Sort subdocument using mongoose (MongoDB)

I am trying to do something very simple but an new to MongoDB! 我正在尝试做一些非常简单的事情,但却是MongoDB的新功能! I have a document called Device and a sub-document called Movement. 我有一个名为Device的文档和一个名为Movement的子文档。 I want to get the last two movement sub-documents out of Device ordered by last_seen (a date). 我想从last_seen (日期)排序的设备中获取最后两个移动子文档。 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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