我正在尝试按日期对评论进行排序,但我无法纠正它。
{
"_id": "5defc10b8e753623b4ad0adf",
"title": "bla bla",
"owner:"idToPopulate",
"comments": [
{
"_id": "5dfc2185e62103121cfc0f18",
"reply": "1",
"replyDate": "2019-12-10T16:00:11.228Z"
},
{
"_id": "5dfc218be62103121cfc0f19",
"reply": "2",
"replyDate": "2019-13-10T16:00:11.228Z"
}
]
}
这是我尝试的方式(结果必须是,最后日期按评论排序)
.sort({"comments.replyDate":1})
答案 0 :(得分:1)
您可以使用$sort对数据进行排序,但是在使用之前,必须先拆分数组。尝试使用此mongo查询:
db.collection.aggregate([
{
$unwind: {
path: "$comments"
}
},
{
$sort: {
"comments.replyDate": -1
}
},
{
$group: {
_id: "$_id",
comments: {
$push: {
_id: "$comments._id",
item: "$comments.reply",
date: "$comments.replyDate"
}
}
}
}
])