本文介绍了如何在mongoose/mongodb中对子文档数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用户(mongodb文档)
user (mongodb document)
{
"_id": "5bccfb7515bc6d0c6872ed91",
"notification": {
"notidata": [
{
"data": {
"para": "Your Ad '1' has been successfully submitted."
},
"notistatus": false,
"_id": "5be35d89113aec40c4ca7517",
"notidate": "2018-11-07T21:47:53.803Z"
},
{
"data": {
"para": "Your Ad '2' has been successfully submitted."
},
"notistatus": false,
"_id": "5be35d92113aec40c4ca7519",
"notidate": "2018-11-07T21:48:02.729Z"
}
],
"counter": 4
},
"ads": [],
"username": "mesam",
"email": "[email protected]",
"password": "0",
"country": "AZE",
"createdOn": "2018-10-21T22:19:33.377Z",
"__v": 0
}
route.js
route.js
User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted."} } }, { new: true }, function (err, df) { ....
我希望按notidate
排序notidata
.使用$postion: 0
无效. $sort: notidate: -1
I want notidata
to be sorted by notidate
. Using $postion: 0
did not work. Nor did $sort: notidate: -1
* $排名尝试失败*
User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted.", "$position": 0} } }, { new: true }, function (err, df) {....
$ sort尝试失败
failed $sort attempt
User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted.", "$sort": {"notification.notidata.notidate": -1}} } }, { new: true }, function (err, df) {....
推荐答案
您必须使用 $ sort 使用$each
运算符,然后您只需指定嵌套字段的名称(而不是示例中的完整路径),请尝试:
You have to use $sort with $each
operator and then you just specify the name of nested field (not entire path like in your example), try:
User.findOneAndUpdate({ _id: user._id }, {
$push: {
"notification.notidata": {
"$each": [ { data: { para: "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted." } } ],
"$sort": {"notidate": -1}
}
}
}, {new: true})
这篇关于如何在mongoose/mongodb中对子文档数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!