【问题标题】:How to sort sub-document array in mongoose/mongodb?如何在 mongoose/mongodb 中对子文档数组进行排序?
【发布时间】:2019-04-11 10:16:28
【问题描述】:

用户(mongodb 文档)

{
  "_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

User.findOneAndUpdate({ _id: user._id }, { $push: { "notification.notidata": { "data.para": "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted."} } }, { new: true }, function (err, df) { ....

我希望notidatanotidate 排序。使用 $postion: 0 不起作用。 $sort: notidate: -1也没有

* $position 尝试失败*

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 尝试失败

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) {....

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您必须将$sort$each 运算符一起使用,然后您只需指定嵌套字段的名称(而不是您的示例中的整个路径),尝试:

    User.findOneAndUpdate({ _id: user._id }, { 
        $push: {
            "notification.notidata": {
                "$each": [ { data: { para: "Your Ad " + "'" + thisad.heading + "'" + " has been successfully submitted." } } ],
                "$sort": {"notidate": -1}
            }
        }
    }, {new: true})
    

    【讨论】:

    • 非常感谢!有效。但是,我希望了解,因为每次在我的应用程序中执行此 User.findOneAndUpdate 时,都会插入 1 个 notidata.para 条目。那为什么像$each这样的东西需要放在$push中呢? $each 不是用于插入多个数据(如数据数组)吗?
    • 我知道这可能会造成混淆,文档中甚至提到如果您只想对元素进行排序,则应该传递空数组。这是设计使然
    • 非常感谢!
    猜你喜欢
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多