为查询创建 MongoDB 聚合管道

问题描述 投票:0回答:1

以下是客户的文档架构。它嵌套了“交易”

{
    "_id": {
        "$oid": "65e797c4d4ed4faa9d4e8425"
    },
    "user_id": "Test1_R_1",
    "email": "lkasdjkhsdkhxsaun+6zcYYU",
    "full_name": "iusakhlknsa==",
    "omnture_hash_key": "Test1_R_1",
    "language": "EN",
    "transaction": {
        "RESPONSE_CODE": "000",
        "SETTLEMENT_CODE": "3",
        "GENDER_FLG": "1",
        "TERM_CITY": "SIOUX FALLS",
        "CUST_AGE": "44",
        "TERM_ID": "CASHDISP_T1"
    },
    "transaction_date": {
        "$date": "2023-04-26T09:53:17.000Z"
    },
    "status": "Exported",
    "status_code": 2,
    "created_date": {
        "$date": "2024-03-05T00:48:29.716Z"
    },
    "last_modified_date": {
        "$date": "2024-03-02T00:45:11.166Z"
    }
}

以下是筛选文档的条件。

Select user_id, email, transaction.* from customer
Group By Email
Having (max(createdDate) = today and max(status_code) < 5) 
And 
(max(lastModifiedDate + 2) < tomorrow) 
Order by createdDate desc, user_id
Where createdDate < 90

上述查询的聚合管道是什么?

mongodb aggregation-framework nosql-aggregation
1个回答
0
投票

我不知道你说的

created_date < 90
是什么意思,但尽管如此,它似乎应该到最顶层。

[
  {
    $match: {
      // created_date: { $lt: (...?) },
    },
  },
  {
    $group: {
      _id: "$user_id",
      email: { $first: "$email" },
      full_name: { $first: "$fullName" },
      transactions: {
        $push: {
          transaction: "$transaction",
          created_date: "$created_date",
        },
      },
      max_status_code: { $max: "$status_code" },
      max_created_date: { $max: "$created_date" },
      max_last_modified_date: {
        $max: "$last_modified_date",
      },
    },
  },
  {
    $unwind: { path: "$transactions" },
  },
  {
    $match: {
      max_created_date: new Date(),
      max_status_code: { $lt: 5 },
      $expr: {
        $lt: [
          {
            $add: [
              "$max_last_modified_date",
              2 * 24 * 60 * 60 * 1000,
            ],
          }, // Add 2 days in milliseconds
          {
            $toDate: {
              $add: [
                new Date(),
                24 * 60 * 60 * 1000,
              ],
            },
          }, // Tomorrow's date in milliseconds
        ],
      },
    },
  },
  {
    $sort: {
      "transaction.created_date": -1,
      user_id: 1,
    },
  },
]
© www.soinside.com 2019 - 2024. All rights reserved.