我是MERN Stack的新手 我尝试编写此查询,但没有任何解决方案就无法在Google上搜索很多内容
表1帖子
--------------------------
|id | title | category |
--------------------------
| 1 | title1 | 1 |
| 2 | title2 | 2 |
| 3 | title3 | 1 |
| 4 | title4 | 1 |
================= 表2类别
---------------
|id | name |
---------------
| 1 | cat1 |
| 2 | cat2 |
==================== 我想要的结果就是这个
---------------------------------
|id | name | number of posts |
---------------------------------
| 1 | cat1 | 3 |
| 2 | cat2 | 1 |
如果有帮助,我可以在mysql中编写此查询
SELECT categories.*,COUNT(posts.id) AS np FROM `categories` JOIN materials ON (categories.id = posts.category) GROUP BY categories.id
谢谢
答案 0 :(得分:1)
您可以尝试在mongodb 3.6中的以下聚合以及更高版本中
db.collection.aggregate([
{ "$lookup": {
"from": "posts",
"let": { "id", "$id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$category", "$$id"] }}},
{ "$count": "count" }
],
"as": "count"
}},
{ "$project": {
"name": 1,
"numberOfPosts": { "$arrayElemAt": ["$count.count", 0] }
}}
])