2016-07-27 85 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 

希望它有助于!