请教大家一个关于 MongoDB 聚合查询的问题

2019-08-23 10:26:51 +08:00
 hengo

能不能在多条MongoDB记录中,聚合查询,一次输出多个字段的总记录条数 比如

{ "month" : 3, "day" : 5, "year" : 2019 }
{ "month" : 2, "day" : 4, "year" : 2018 }
{ "month" : 3, "day" : 1, "year" : 2018 }
{ "month" : 5, "day" : 2, "year" : 2019 }
{ "month" : 5, "day" : 1, "year" : 2019 }

比如一次性查询: { month = 3, year = 2019 }

输出结果集: { monthCount = 2, yearCount = 3}

现在我只能根据字段去查找记录数,不能去给字段匹配相应的值去查询。

1199 次点击
所在节点    问与答
7 条回复
lwd219
2019-08-23 14:21:17 +08:00
aggregate ?
licht114
2019-08-23 14:53:05 +08:00
坐等 MongoDB 大神,我也想知道有没有骚操作
hengo
2019-08-23 15:02:41 +08:00
@lwd219 对,以前我是一个一个查的,效率比较低,因为我们这边数据量可能比较大,所以想一次性查,效率稍微高一点。
Philippa
2019-08-23 15:45:59 +08:00
```
{
"$group": {
"_id": null,
"month": {
'$sum': {
'$cond': [
{'$eq': ["$month", "3"]},
1, 0
]
}
},
"year": {
'$sum': {
'$cond': [
{'$eq': ["$year", "2019"]},
1, 0
]
}
},
}
},
{$project: { 'year': 1, 'month': 1, _id: 0 } }
```
没测过
phpdever
2019-08-23 17:02:06 +08:00
phpdever
2019-08-23 17:03:59 +08:00
@licht114 看我回复
licht114
2019-09-06 09:27:15 +08:00
@phpdever 感谢大神分享

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

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

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

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

© 2021 V2EX