可能是这样的:
选项1:
$筛选器/$大小(如果没有同名的重复记录,则更快更有效)
db.collection.aggregate([
{
"$addFields": {
"WentTo": {
$size: {
"$filter": {
"input": "$WentTo",
"as": "w",
"cond": {
"$eq": [
"$$w.Destination.Country",
"Italy"
]
}
}
}
}
}
},
{
$project: {
"Times in Italy": "$WentTo",
Name:1
}
}
])
解释:
-
使用addFields和$filter仅匹配以意大利为国家的数组元素,并使用$size对其进行计数
-
将“WentTo”数组投影为“Times in Italy”,并根据要求命名。
Playground 1
选项2:
这是您的查询,有一些小的更正,也涵盖了每个名称都有模糊记录的情况,请注意,对于较大的集合$展开操作可能会影响性能且速度较慢。。。
db.collection.aggregate([
{
$unwind: "$WentTo"
},
{
$match: {
"WentTo.Destination.Country": "Italy"
}
},
{
$group: {
_id: "$Name",
"Times in Italy": {
$sum: 1
}
}
}
])
Playground 2