【发布时间】:2014-09-08 03:12:00
【问题描述】:
在 mysql 中,我有一个类似的查询:
mysql> SELECT user_id, count(user_id) as dup FROM addressbook GROUP BY user_id HAVING dup>20 ORDER BY dup;
会返回:
+---------+------+
| user_id | dup |
+---------+------+
| 3052 | 21 |
| 996 | 23 |
| 46 | 25 |
| 2709 | 26 |
| 1756 | 28 |
| 43 | 30 |
| 224 | 30 |
| 98 | 32 |
| 289 | 35 |
| 208 | 40 |
| 888 | 43 |
| 4974 | 44 |
| 31 | 46 |
| 166 | 65 |
| 4560 | 99 |
| 85 | 112 |
| 280 | 124 |
| 27 | 166 |
| 2582 | 304 |
| 45 | 476 |
| 3830 | 932 |
| 232 | 1514 |
+---------+------+
22 rows in set (0.01 sec)
当我尝试在 MongoDB 中复制相同的内容时,我无法正确地制定它!
我的收藏类似于
> db.users.find({ }).pretty();
{
"_id" : ObjectId("540c83f9d901f28b921a328c"),
"providers" : [
"local"
],
"loginAttempts" : 0,
"company" : ObjectId("540c83f9d901f28b921a328a"),
"group" : "company-admin",
"firstName" : "Desmond",
"emailVerified" : true,
"addressBook" : [
{
"company" : "emilythepemily",
"contact" : "Miss e m a Hudson",
"address" : ObjectId("540c83f9d901f28b921a328d")
},
{
"company" : "Hughes",
"contact" : "Liam P Hughes",
"address" : ObjectId("540c83f9d901f28b921a328e")
},
...
这是我目前所拥有的:
> db.users.aggregate({ $unwind : "$addressBook" }, { $group: { _id: '',count: { $sum: 1 }}})
{ "result" : [ { "_id" : "", "count" : 6705 } ], "ok" : 1 }
但这给了我所有地址簿条目的总数,我如何返回每个用户记录的总数并根据 mysql 输出列出?
非常感谢任何建议。
【问题讨论】:
-
你的 $group _id 是空的,这就是聚合没有发生的原因。你能进一步解释你想要 mongo 明智的结果吗?
标签: mongodb