我试图根据其状态按类型返回请求总数:
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,
},
...
]
答案 0 :(得分:1)
尝试这种方法,
根据状态
按类型返回请求总数
现在获取不同状态计数的最简单方法是在状态字段中使用带有$ group的聚合管道
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
希望它能帮助!!