每个类别expressjs猫鼬的“查询”计数帖子

时间:2018-09-22 02:02:05

标签: node.js mongodb express mongoose aggregation-framework

我是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

谢谢

1 个答案:

答案 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] }
  }}
])
相关问题