这是我的问题。我在网站上检查了很多其他MongoDB问题,但没有一个符合我的条件。
我有一个MongoDB嵌入式文档结构,如下所示: -
{
company : "ABC",
year : 2010,
Project : [{
Domain : "Telecom",
Client: [{"Name": "Ponderfone","size":25},{"Name": "Skytel","size":35},{"Name": "ChinaTel","size":10}]
}, {
Domain : "Retail",
Client: [{"Name": "Gatemart","size":95},{"Name": "Clearway","size":40}]
}, {
Domain : "Finance",
Client: [{"Name": "MFCI","size":20},{"Name": "FCCI","size":20},{"Name": "MobiBank","size":35}]
}
]
}
{
company : "ABC",
year : 2011,
Project : [{
Domain : "Telecom",
Client: [{"Name": "Ponderfone","size":50},{"Name": "Skytel","size":30},{"Name": "ChinaWay","size":30}]
}, {
Domain : "Retail",
Client: [{"Name": "Gatemart","size":120},{"Name": "Shadowfax","size":15}]
}, {
Domain : "Finance",
Client: [{"Name": "Reuben Analysts","size":15},{"Name": "FCCI","size":10},{"Name": "MobiBank","size":35}]
}
]
}
这里的问题是我正在尝试聚合最里面的文档中的一个列,其中嵌入了两个级别: - " Project.Client.Size"
我正在尝试为特定域(如果您看到JSON)
总结此列db.projects.aggregate(
{ $match: {"year" : 2010,"company" :"ABC"}},
{ $unwind: "$Project" },
{ $match: { $or: [{"Project.Domain" : /Telecom/},{"Project.Domain" :/Retail/}]}},
{ $group: { "_id": {company: "$company", year: "$year", domain: "$Project.Domain"},
headcount: { "$sum":" $Project.Client.size" }}
})
此代码的问题在于它返回结果,其中人数标记为0.
{ "_id" : { "company" : "ABC", "year" : 2010, "domain" : "Retail" }, "headcount"
: 0 }
{ "_id" : { "company" : "ABC", "year" : 2010, "domain" : "Telecom" }, "headcount
" : 0 }
电信,2010年和公司ABC的人数应为(25 + 35 + 10)70 对于零售业,2010年和公司ABC,员工人数应为(95 + 40)135
我在这里缺少什么吗?
答案 0 :(得分:1)
您在管道中的最后一个 $unwind
过滤器之后缺少 $match
管道步骤。这对于Client
数组的非规范化是必要的,这样您就可以在下一个 $group
管道中访问其属性以进行聚合。因此,您的最终管道应遵循以下模式:
db.projects.aggregate([
{ "$match": {"year": 2010, "company": "ABC"} },
{ "$unwind": "$Project" },
{ "$match": { "$or": [{"Project.Domain": /Telecom/},{"Project.Domain": /Retail/}] } },
{ "$unwind": "$Project.Client" },
{
"$group": {
"_id": {
"company": "$company",
"year": "$year",
"domain": "$Project.Domain"
},
"headcount": { "$sum": "$Project.Client.size" }
}
}
])