2016-07-27 82 views
0

我試圖通過類型根據他們的狀態請求總數的返回:多條件求和

  • 如果沒有狀態設置,請求應加requested
  • 如果狀態是下令,請求應加ordered
  • 如果狀態趕到,請求應加arrived

    caseRequest.aggregate([{ 
        $group: { 
        _id: "$product", 
        suggested: { 
         $sum: { 
          $cond: [{ 
          $ifNull: ["$status", true] 
          }, 
          1, 0 
         ]} 
        }, 
        ordered: { 
         $sum: { 
         $cond: [{ 
           $eq: ["$status", "ordered"] 
          }, 
          1, 0 
         ] 
         } 
        }, 
        arrived: { 
         $sum: { 
         $cond: [{ 
          $eq: ["$status", "arrived"] 
          }, 
          1, 0 
         ] 
         } 
        } 
        } 
    } 
    

但由於某些原因沒有找到下令或任何請求狀態到達。如果在數據庫中,我有48請求,其中45無狀態,2有序和1趕到時,它返回:

[ 
    { 
     _id: "xxx", 
     suggested: 48, 
     ordered: 0, 
     arrived: 0, 
    }, 
    ... 
] 

回答

1

試試這個辦法,

返回總數的根據他們的狀態

我們得到的不同狀態計數最簡單的方式按類型的請求是對狀態字段使用聚合管道與$組

db.stackoverflow.aggregate([{ $group: {_id: "$status", count: {$sum:1}} }]) 

我們將得到一個結果與此類似

{ "_id" : "", "count" : 2 } 
{ "_id" : "arrived", "count" : 3 } 
{ "_id" : "ordered", "count" : 4 } 

這是用來檢索這些記錄的模式很簡單,這樣它會更容易理解。該模式將對文件和狀態值的最高等級的參數可以被「訂購」,「到達」或空

模式

{ "_id" : ObjectId("5798c348d345404e7f9e0ced"), "status" : "ordered" }

的集合填充9條記錄,狀態爲已訂購,已到達併爲空

db.stackoverflow.find() 
{ "_id" : ObjectId("5798c348d345404e7f9e0ced"), "status" : "ordered" } 
{ "_id" : ObjectId("5798c349d345404e7f9e0cee"), "status" : "ordered" } 
{ "_id" : ObjectId("5798c34ad345404e7f9e0cef"), "status" : "ordered" } 
{ "_id" : ObjectId("5798c356d345404e7f9e0cf0"), "status" : "arrived" } 
{ "_id" : ObjectId("5798c357d345404e7f9e0cf1"), "status" : "arrived" } 
{ "_id" : ObjectId("5798c358d345404e7f9e0cf2"), "status" : "arrived" } 
{ "_id" : ObjectId("5798c35ad345404e7f9e0cf3"), "status" : "ordered" } 
{ "_id" : ObjectId("5798c361d345404e7f9e0cf4"), "status" : "" } 
{ "_id" : ObjectId("5798c362d345404e7f9e0cf5"), "status" : "" } 

db.stackoverflow.count() 
9 

希望它有助於!