MongoDB 聚合查询问题?

2019-07-05 11:20:27 +08:00
 moodasmood

我有个类似这样的数据结构

{
"address":[
"北京",
"朝阳区",
"京旺家园"
],
....
}

现在我如果需要统计全北京的总数得怎么查呢?

db.cityLogs.aggregate([
    { '$unwind': '$address' }
    , {
        $group: { _id: "$address", count: { $sum: 1 } }
    }
])

我这样查出来是按小区分组的。

1698 次点击
所在节点    程序员
5 条回复
raysmond
2019-07-05 14:25:32 +08:00
$unwind 可以将数组打平,不过好像是 MongoDB 3.2 以上才有的 feature
Vegetable
2019-07-05 14:47:37 +08:00
没明白,你想统计所有北京出现的次数?你的方法是可行的,中间需要插一步 match.
heanhsu
2019-07-05 17:08:10 +08:00
不知道是不是这个意思

db.cityLogs.aggregate([
{
$unwind:'$address'
},
{
$group:{
_id: "$_id",
city:{
$first:'$address'
}
}
},
{
$group:{
_id: '$city',
count:{
$sum:1
}
}
}
])
heanhsu
2019-07-05 17:09:42 +08:00
不知道是不是这个意思


```

db.cityLogs.aggregate([
{
$unwind:'$address'
},
{
$group:{
_id: "$_id",
city:{
$first:'$address'
}
}
},
{
$group:{
_id: '$city',
count:{
$sum:1
}
}
}
])

```
moodasmood
2019-07-05 18:22:18 +08:00
@Vegetable
@heanhsu

多谢,确实加个 match 就行了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/580245

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX