Arrays 聚集MongoDB中的计数
我有一份文件,其中包含在世界各地都设有办事处的公司。这些办公室排成一排。价值观之一是Arrays 聚集MongoDB中的计数,arrays,mongodb,count,aggregation-framework,Arrays,Mongodb,Count,Aggregation Framework,我有一份文件,其中包含在世界各地都设有办事处的公司。这些办公室排成一排。价值观之一是城市,我需要确切知道哪些公司在“旧金山”有两个办事处 该文件: _id:52cdef7c4bab8bd675297d8b name:"AdventNet" . . . . Offices:Array 0: Description:"Headquarters" . . city:"San Francisco"
城市
,我需要确切知道哪些公司在“旧金山”有两个办事处
该文件:
_id:52cdef7c4bab8bd675297d8b
name:"AdventNet"
.
.
.
.
Offices:Array
0:
Description:"Headquarters"
.
.
city:"San Francisco"
我的解决方案:
db.companies.aggregate(
{$group:{_id:{city:"$offices.city"},count:{$sum:1}}},
{$match:{$and: [{"_id.city":"San Francisco"},{count:2}]}})
但它不起作用。
有什么想法吗?演示-
迭代$filter
的循环,并按“旧金山”过滤城市city
获取过滤后城市的大小$size
- 匹配表达式
城市的条件大小为2$expr
db.collection.aggregate([
{
$match: { "Offices.city": "San Francisco" } // filter to reduce records going to $map in the next pipeline
},
{
$set: {
haveOfficeInCIty: {
$size: { // get the size of the filtered array
$filter: { // filter the array
input: "$Offices",
as: "office",
cond: {
$eq: [ "$$office.city", "San Francisco" ] // filter by city
}
}
}
}
}
},
{
$match: {
haveOfficeInCIty: { $eq: 2 } // filter where count is 2
}
}
])
db.collection.aggregate([
{
$match: {
$expr: {
$eq: [
{
$size: {
$filter: {
input: "$Offices.city",
cond: { $eq: ["$$this", "San Francisco"] }
}
}
},
2
]
}
}
}
])