我需要一种对数组进行分组和计数的方法。我要实现的是按“类型”计算退货数量
以下是我的部门文档的外观
{
"_id" : ObjectId("1234566789"),
"jobStatus" : "OK",
"request" :
{
"header" : {
"timestamp" : "2020-10-21 00:00:00.000Z",
"action" : "importAction",
"type" : "registration"
},
"body" : [{
"system_header" : {
"student" : "2019051",
"course" : "Business"
}
}]
}
}
当指望我做了以下第一次搜索
db.department.aggregate(
[{
$match: {
sysDateI: {
$gt: ISODate("2020-10-18 22:00:00.000Z"),
$lt: ISODate("2020-10-19 22:00:00.000Z")
}
}
}, {
$group: {
_id: '$request.header.type',
COUNT: {
$sum: 1
}
}
}]
)
并产生了令人满意的以下
/* 1 */
{
"_id" : "alumni",
"COUNT" : 3
}
/* 2 */
{
"_id" : "graduation",
"COUNT" : 5
}
/* 3 */
{
"_id" : "registration",
"COUNT" : 43
}
但是,当我尝试使用下面的内容计算“ body”部分中的内容时,它返回数组的内容而不是求和
编码
db.department.aggregate(
[{
$match: {
sysDateI: {
$gt: ISODate("2020-10-18 22:00:00.000Z"),
$lt: ISODate("2020-10-19 22:00:00.000Z")
}
}
}, {
$group: {
_id: '$request.body.system_header.course',
COUNT: {
$sum: 1
}
}
}]
)
结果如下
{
"_id":[
"Education",
"Education",
"Education",
"Business",
"Science"
],
"COUNT" : 1.0
}
我需要退货的是这样的。我确实意识到system_header是一个数组。
{
"_id":"Business",
"COUNT":45
}
{
"_id":"Education",
"COUNT":3
}
您的指导将不胜感激
嗨,在这样的组之前添加$ unwind:
db.department.aggregate(
[{
$match: {
sysDateI: {
$gt: ISODate("2020-10-18 22:00:00.000Z"),
$lt: ISODate("2020-10-19 22:00:00.000Z")
}
}
},
{
$unwind: "$request.body"
},
{
$group: {
_id: '$request.body.system_header.course',
COUNT: {
$sum: 1
}
}
}]
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句