[英]How to query and sort Mongoose subdocuments
I need to get the card
inside of deck
which has the lowest stats.reviewDate
value.我需要将card
放入deck
组中,它的stats.reviewDate
值最低。
For example, a query on this:例如,对此的查询:
{
"_id": "608642db80a36336946620aa",
"cards": [
{
"stats": {
"reviewDate": "1985-03-26T04:34:17.425Z",
},
"_id": "6086430080a36336946620ab",
"front": "front",
"back": "back"
},
{
"stats": {
"reviewDate": "2021-05-26T04:34:17.425Z",
},
"_id": "6086430080a36336946620ab",
"front": "front",
"back": "back"
},
{
"stats": {
"reviewDate": "2021-04-26T04:34:17.425Z",
},
"_id": "6086430080a36336946620ab",
"front": "front",
"back": "back"
}
]
}
should return:应该返回:
{
"stats": {
"reviewDate": "1985-03-26T04:34:17.425Z",
},
"_id": "6086430080a36336946620ab",
"front": "front",
"back": "back"
}
I've tried to achieve this by sorting the cards in descending order, and reading the first item in the list:我试图通过按降序对卡片进行排序并读取列表中的第一项来实现这一点:
DeckModel.findById(req.params.deckId, 'cards')
.sort({'cards.stats.dateCreated': 'desc'})
.exec((err, docs) => {
if(err) { return next(err) }
console.log(docs.cards.[0]);
});
But it doesn't work - certainly due to my poor understanding of.sort())但它不起作用——当然是因为我对.sort()的理解很差)
Here is a similar question to mine, although it has no accepted answer. 这是一个与我类似的问题,尽管它没有被接受的答案。
How would one construct a query that returns my desired result?如何构建一个返回我想要的结果的查询?
Here are my schemas, if needed:如果需要,这是我的模式:
var DeckSchema = new Schema (
{
title: { type: String, required: true, maxlength: 255 },
cards: [CardSchema]
}
)
var CardSchema = new Schema(
{
stats: {
reviewDate: {type: Date, default: Date.now(), required: true},
},
front: String,
back: String
}
)
Thanks all,谢谢大家,
Demo - https://mongoplayground.net/p/RUssJuB7XO2演示 - https://mongoplayground.net/p/RUssJuB7XO2
db.collection.aggregate([
// { $match: { } }, your query here
{ $unwind: "$cards" },
{ $sort: { "cards.stats.dateCreated": -1 } },
{ $limit: 1 },
{ $replaceRoot: { "newRoot": "$cards" } }
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.