Mat*_*off 43 mongodb aggregation-framework
假设我的MongoDB架构如下所示:
{car_id: "...", owner_id: "..."}
Run Code Online (Sandbox Code Playgroud)
这是一种多对多的关系.例如,数据可能如下所示:
+-----+----------+--------+
| _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
+-----+----------+--------+
Run Code Online (Sandbox Code Playgroud)
我想获得每个所有者拥有的汽车数量.在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;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,结果将如下所示:
+----------+------------+
| owner_id | cars_owned |
+----------+------------+
| 1 | 3 |
| 2 | 2 |
| 3 | 4 |
+----------+------------+
Run Code Online (Sandbox Code Playgroud)
如何使用聚合框架使用MongoDB完成同样的事情?
Joh*_*yHK 71
为了适应潜在的重复项,您需要使用两个$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);
}
);
Run Code Online (Sandbox Code Playgroud)
给出格式为的结果:
[ { cars_owned: 2, owner_id: 10 },
{ cars_owned: 1, owner_id: 11 } ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53782 次 |
| 最近记录: |