【问题标题】:How do I paginate and sort sub-document array MongoDB如何对子文档数组 MongoDB 进行分页和排序
【发布时间】:2021-12-03 08:16:35
【问题描述】:

我正在尝试对子文档数组进行分页和排序。但它不起作用。我需要对这个 transactionHistory 数组进行分页。 每页 = 2; 有人会如何以最简单/最有效的方式来做这件事?

{
        "_id": "619623e27525bd59cd5dbaa4",
        "nidNumber": 123456789,
        "referralCode": "12345",
        "transactionHistory": [
            {
                "transactionId": {
                    "_id": "61a8749758a558600557f0fd",
                    "amount": 500,
                    "createdAt": "2021-12-02T07:24:07.653Z",
                    "updatedAt": "2021-12-02T07:24:07.653Z",
                },
                "_id": "61a8749758a558600557f100"
            },
            {
                "transactionId": {
                    "_id": "61a8755dc0c3aa99c5ae45d3",
                    "amount": 500,
                    "createdAt": "2021-12-02T07:27:25.384Z",
                    "updatedAt": "2021-12-02T07:27:25.384Z",
                },
                "_id": "61a8755dc0c3aa99c5ae45d6"
            },
            {
                "transactionId": {
                    "_id": "61a875e9be563a549fa209db",
                    "amount": 50,
                    "createdAt": "2021-12-02T07:29:45.042Z",
                    "updatedAt": "2021-12-02T07:29:45.042Z",
                },
                "_id": "61a875e9be563a549fa209de"
            },
            {
                "transactionId": {
                    "_id": "61a87e57dbe5bc661900244a",
                    "amount": 50,
                    "createdAt": "2021-12-02T08:05:43.018Z",
                    "updatedAt": "2021-12-02T08:05:43.018Z",
                },
                "_id": "61a87e57dbe5bc661900244d"
            },
            {
                "transactionId": {
                    "_id": "61a8863607ffafc2f598b032",
                    "amount": 50,
                    "createdAt": "2021-12-02T08:39:18.289Z",
                    "updatedAt": "2021-12-02T08:39:18.289Z",
                },
                "_id": "61a8863607ffafc2f598b035"
            }
        ]
    }

【问题讨论】:

    标签: node.js mongodb pagination


    【解决方案1】:

    使用$unwind

    db.collection.aggregate([
      {
        "$match": {
          "_id": "619623e27525bd59cd5dbaa4"
        }
      },
      {
        "$unwind": "$transactionHistory"
      },
      {
        "$sort": {
          "transactionHistory.transactionId.createdAt": 1
        }
      },
      {
        "$skip": 2
      },
      {
        "$limit": 2
      }
    ])
    

    mongoplayground

    【讨论】:

    • 感谢您对这些数据进行排序。你能分页这个数组吗?
    • @SakilKhan 我更新了我的答案
    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    相关资源
    最近更新 更多