我有以下模式:
const userSchema = new Schema({
local: {
email: {type: String, unique: true, sparse: true, lowercase: true, trim: true, required: true},
password: {type: String, required: true},
},
username: {type: String, unique: true, lowercase: true, trim: true},
Items: [{
name: {type: String, trim: true},
createdAt: {type: Date, default: Date.now}
}]
});我使用以下查询检索所有项目:
User.findById(req.user.id, 'Items -_id', (err, user) => { ... });返回以下内容:
{ Items:
[
{ name: 'test1',
_id: 58c70800a03d09a31bb7fc17,
createdAt: Mon Mar 13 2017 20:58:40 GMT+0000 (GMT) },
{ name: 'test2',
_id: 58c70826a03d09a31bb7fc18,
createdAt: Mon Mar 13 2017 20:59:18 GMT+0000 (GMT) }
]
},我的问题是:如何编辑我的猫鼬查询,以返回基于createdAt属性按降序排序的Items数组中的对象?也就是说,test2出现在test1之上。
(一些附加信息,每个用户的条目数组平均长度为3-10个,我使用Nodejs作为后端,出于这个原因,由于Nodejs单线程特性,在应用程序端排序数组是可以忍受的,因为它的大小很小或者效率太低?),谢谢。
发布于 2017-03-14 00:03:34
您可以使用聚合来匹配您的_id、展开Items数组、执行降序排序和只项目Items字段:
User.aggregate([{
"$match": {
"_id": new mongoose.mongo.ObjectId("58c7fa6987200dfc592d088c")
}
}, {
"$unwind": "$Items"
}, {
"$sort": {
"Items.createdAt": -1
}
}, {
"$group": {
"Items": {
"$push": "$Items"
},
"_id": 1
}
}, {
"$project": {
"_id": 0,
"Items": 1
}
}], function(err, res) {
console.log(res);
})https://stackoverflow.com/questions/42775146
复制相似问题