我的mongo-db输入中的下列数据:
[
{
'id':1,
"year": "2022-10-01",
"Area":{
"Education":'Engineering'
}
},
{
'id':2,
"year": "2022-10-01",
"Area":{
"Education":'Commerce'
}
},
{
'id':3,
"year": "2022-10-01",
"Area":{
"Education":'Arts'
}
},
{
'id':4,
"year": "2022-10-01",
"Area":{
"Education":'Arts'
}
},
{
'id':5,
"year": "2022-01-01",
"Area":{
"Education":'Engineering'
}
},
{
'id':6,
"year": "2022-01-01",
"Area":{
"Education":'Engineering'
}
}
]根据每个教育字段有几年的记录,最终结果将以这种形式进行,首先按日期分组,然后按教育字段分组,以及每年每个教育字段的计数
以这种方式取得的成果:
{
"2022-10-01": {
"Education": {
"Engineering": 1,
"Commerce": 1,
"Arts": 2
}
},
"2021-01-01": {
"Education": {
"Engineering": 2,
"Commerce": 0,
"Arts": 0
}
}
}发布于 2022-06-07 13:53:10
试试这个:
db.collection.aggregate([
{ $group: { _id: { year: "$year", Education: "$Area.Education" }, count: { $sum: 1 } } },
{ $group: { _id: "$_id.year", Education: { $push: { k: "$_id.Education", v: "$count" } } } },
{ $set: { k: "$_id", Education: { $arrayToObject: "$Education" } } },
{ $group: { _id: null, root: { $push: { k: "$_id", v: { Education: "$Education" } } } } },
{ $replaceWith: { $arrayToObject: "$root" } }
])计算不存在的值有点困难,因为可能有无穷多的值。也许是这样的:
db.collection.aggregate([
{ $group: { _id: { year: "$year", Education: "$Area.Education" }, count: { $sum: 1 } } },
{ $group: { _id: "$_id.year", Education: { $push: { k: "$_id.Education", v: "$count" } } } },
{
$set: {
Education: {
$map: {
input: ["Engineering", "Arts", "Commerce"],
in: {
k: "$$this",
v: {
$let: {
vars: {
val: {
$first: {
$filter: {
input: "$Education",
as: "area",
cond: { $eq: ["$$this", "$$area.k"] }
}
}
}
},
in: { $ifNull: ["$$val.v", 0] }
}
}
}
}
}
}
},
{ $set: { k: "$_id", Education: { $arrayToObject: "$Education" } } },
{ $group: { _id: null, root: { $push: { k: "$_id", v: { Education: "$Education" } } } } },
{ $replaceWith: { $arrayToObject: "$root" } }
])https://stackoverflow.com/questions/72531764
复制相似问题