簡體   English   中英

mongoose聚合中如何根據狀態對數據進行排序

[英]How to sort data according to the status in mongoose aggregation

我在委托收藏中有很多記錄。

{
    "_id": "5f2b96508082a30d27581cf7", 
    "createdAt": "2020-08-06T05:34:08.281Z",
    "supplierName": "John Cena", 
    "status": "Created", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2b996d8082a30d27581cf9",
    "createdAt": "2020-08-05T05:34:08.281Z", 
    "supplierName": "John Cena",
    "status": "Pending", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2ba2e28082a30d27581cfe", 
    "createdAt": "2020-08-05T05:34:08.281Z",
    "supplierName": "John Cena",
    "status": "Accepted", 
    "commissionID": "5f2b96508082a30d27581cf6"
},

{
    "_id": "5f2ba2ea8082a30d27581cff", 
    "createdAt": "2020-08-04T05:34:08.281Z",
    "supplierName": "John Cena",
    "status": "Pending", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2ba2ea8082a30d27581cff", 
    "createdAt": "2020-08-03T03:34:08.281Z",
    "supplierName": "John Cena",
    "status": "Rejected", 
    "commissionID": "5f2b96508082a30d27581cf6"
}

我需要在 desc 中按 Pending 狀態和 createdAt 進行排序(我的意思是頂部的所有待處理記錄以及 createdAt 日期 desc 順序)

狀態 = Created, Pending, Accepted, Rejected

應該是這樣的

{
    "_id": "5f2b996d8082a30d27581cf9",
    "createdAt": "2020-08-05T05:34:08.281Z", 
    "supplierName": "John Cena",
    "status": "Pending", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2ba2ea8082a30d27581cff", 
    "createdAt": "2020-08-04T05:34:08.281Z",
    "supplierName": "John Cena",
    "status": "Pending", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2b96508082a30d27581cf7", 
    "createdAt": "2020-08-06T05:34:08.281Z",
    "supplierName": "John Cena", 
    "status": "Created", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2ba2e28082a30d27581cfe", 
    "createdAt": "2020-08-05T05:34:08.281Z",
    "supplierName": "John Cena",
    "status": "Accepted", 
    "commissionID": "5f2b96508082a30d27581cf6"
},
{
    "_id": "5f2ba2ea8082a30d27581cff", 
    "createdAt": "2020-08-03T05:34:08.281Z",
    "supplierName": "John Cena",
    "status": "Rejected", 
    "commissionID": "5f2b96508082a30d27581cf6"
}

我正在使用 mongodb 3.4、mongoose 和 node.js。 請幫我。

您可以通過自定義訂購來做到這一點。

db.collection.aggregate([
  {
    $addFields: {
      sortId: {
        $cond: [
          {
            $eq: [ //If pending
              "$status",
              "Pending"
            ]
          },
          0, //then 0
          {
            $cond: [
              { //Else if created
                $eq: [
                  "$status", 
                  "Created"
                ]
              },
              1, //then 1
              2 //Else 2
            ]
          }
        ]
      }
    }
  },
  {
    $sort: {
      sortId: 1
    }
  }
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM