我的MongoDB数据库有一个'interview'集合,它的文档结构类似于:
{
"_id" : ObjectId("632b97b0f2bd3f64bbc30ec8"),
"agency" : "AG1",
"year" : "2022",
"month" : "9",
"residents" : [
{
"sequential" : 1,
"name" : "Resident 1",
"statusResident" : "pending",
},
{
"sequential" : 2,
"name" : "Resident 2",
"statusResident" : "not analyzed"
},
{
"sequential" : 3,
"name" : "Resident 3",
"statusResident" : "not analyzed"
},
{
"sequential" : 4,
"name" : "Resident 4",
"statusResident" : "finished"
}
]
}
{
"_id" : ObjectId("882b99b0f2bd3f64xxc30ec8"),
"agency" : "AG2",
"year" : "2022",
"month" : "9",
"residents" : [
{
"sequential" : 1,
"name" : "Resident 10",
"statusResident" : "pending",
},
{
"sequential" : 2,
"name" : "Resident 20",
"statusResident" : "not analyzed"
}
]
}
我想创建一个查询,返回类似于SQL SELECT agency, statusResident, COUNT(*) FROM interviews GROUP BY agency, statusResident
的内容。
对于上面的这些文档,将返回类似于
AG1 pending 1
AG1 not analyzed 2
AG1 finished 1
AG2 pending 1
AG2 not analyzed 1
我运行了以下查询,但它们没有返回我所需的内容:
db.interviews.aggregate([
{ $group: { _id: { agency: "$agency", statusResident: "$residents.statusResident", total: { $sum: "$residents.statusResident" } } } },
{ $sort: { agency: 1 } }
db.interviews.group({
key:{agency:1, "residents.statusResident":1},
cond:{year:2022},
reduce:function(current, result)
{
result.total += 1;
},
initial:{total:0}
})
我已经查阅了post“MongoDB SELECT COUNT GROUP BY“和“Select count group by mongodb“以及MongoDB文档,但是没有任何结果。我应该运行什么查询来获得与我想要的结果相似的结果?
2条答案
按热度按时间vsaztqbk1#
试试这个
Mongo Playground
z0qdvdin2#
您可以尝试以下查询:
$unwind
解构数组,也可以按statusResident
分组。$group
乘以两个值,agency
和statusResident
。$project
,以获得更易于读取的输出。示例here