假设我的MongoDB模式如下所示:

{car_id: "...", owner_id: "..."}

这是一种多对多的关系.例如,数据可能如下所示:

+-----+----------+--------+
| _id | owner_id | car_id |
+-----+----------+--------+
|   1 |        1 |      1 |
|   2 |        1 |      2 |
|   3 |        1 |      3 |
|   4 |        2 |      1 |
|   5 |        2 |      2 |
|   6 |        3 |      4 |
|   7 |        3 |      5 |
|   8 |        3 |      6 |
|   9 |        3 |      7 |
|  10 |        1 |      1 | <-- not unique
+-----+----------+--------+

我想知道每个车主拥有的汽车数量.在SQL中,这可能看起来像:

SELECT owner_id, COUNT(*) AS cars_owned
FROM (SELECT owner_id FROM car_owners GROUP BY owner_id, car_id) AS t
GROUP BY owner_id;

在本例中,结果如下所示:

+----------+------------+
| owner_id | cars_owned |
+----------+------------+
|        1 |          3 |
|        2 |          2 |
|        3 |          4 |
+----------+------------+

我如何使用MongoDB和聚合框架来完成同样的事情?

推荐答案

为了适应潜在的重复,您需要使用两个$group操作:

db.test.aggregate([
    { $group: {
        _id: { owner_id: '$owner_id', car_id: '$car_id' }
    }},
    { $group: {
        _id: '$_id.owner_id',
        cars_owned: { $sum: 1 }
    }},
    { $project: {
        _id: 0,
        owner_id: '$_id',
        cars_owned: 1
    }}]
    , function(err, result){
        console.log(result);
    }
);

以以下格式给出结果:

[ { cars_owned: 2, owner_id: 10 },
  { cars_owned: 1, owner_id: 11 } ]

Mongodb相关问答推荐

没有文档的MongoDB集合中的不一致,但当我执行count()时,它告诉我有15个文档

如何填充Mongoose中的嵌套引用

获取响应周期中的特定键和值

从MongoDB迁移到PostgreSQL:为PostgreSQL编写聚合管道查询

优化游戏应用程序的反馈表单后端设计

MongoDB 按日期时间字段查询 1h 间隔

pymongo - ifnull 重新调整整个对象而不是特定字段

构造函数的参数 0 需要错误类型的 bean

mongo _id 字段重复键错误

我怎样才能排序空值在 mongodb 中是最后排序的?

在 Nodejs 中找不到模块

Springboot 使用 find*() 查询时出现 Mongodb 错误

是否有适用于 Linux 的 MongoDB GUI 桌面应用程序?

MongoDB Java API:put() 与 append()

MEAN 堆栈文件上传

MongoException: Index with name: code already exists with different options

MongoDB服务器仍然可以在没有凭据的情况下访问

Mongodb错误:The positional operator did not find the match needed from the query

处理Mongodb连接的正确方法是什么?

Mongodb 按字段名称查找任何值