MongoDB中的数据具有以下准备聚合功能1
{"_id" : { "monthDate":"04-03-2020"}, "Job" : [ "Designer","Tester","Designer"]}
{"_id" : { "monthDate":"14-03-2020"}, "Job" : [ "Designer","Tester","Tester"]}
{"_id" : { "monthDate":"24-03-2020"}, "Job" : [ "Developer","Manager"]}
{"_id" : { "monthDate":"25-03-2020"}, "Job" : [ "Developer","Developer","Developer"]}
我需要以下输出
{"_id" : { "monthDate":"04-03-2020"}, "Job" : [ "Designer":2,"Tester":1]}
{"_id" : { "monthDate":"14-03-2020"}, "Job" : [ "Designer":1,"Tester":2]}
{"_id" : { "monthDate":"24-03-2020"}, "Job" : [ "Developer":1,"Manager":1]}
{"_id" : { "monthDate":"25-03-2020"}, "Job" : [ "Developer":3]}
你可以试试,
$setUnion
从Job
数组中获得唯一的数组$map
从上述操作迭代唯一数组的循环$filter
从主Job
数组中获取匹配标签,并$size
从过滤器中获取匹配标签总数$arrayToObject
将k(key)和v(value)格式转换为对象格式db.collection.aggregate([
{
$addFields: {
Job: {
$arrayToObject: {
$map: {
input: { $setUnion: "$Job" },
as: "j",
in: {
k: "$$j",
v: {
$size: {
$filter: {
input: "$Job",
cond: { $eq: ["$$this", "$$j"] }
}
}
}
}
}
}
}
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句