如何在mongoose/mongodb中对子文档数组进行排序? [英] How to sort sub-document array in mongoose/mongodb?

查看:630
本文介绍了如何在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": "mesam@hotmal.com",
  "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) {....

推荐答案

您必须使用

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中对子文档数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆