【问题标题】:"query" count posts for each category expressjs mongoose“查询”计算每个类别 expressjs mongoose 的帖子
【发布时间】:2019-02-26 09:39:18
【问题描述】:

我是 MERN 堆栈的新手 我试图写这个查询,但我不能在没有任何解决方案的情况下在谷歌上搜索很多

我必须为帖子设置一个表,为类别设置第二个表

表 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

谢谢你

【问题讨论】:

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


    【解决方案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] }
      }}
    ])
    

    【讨论】:

    • 我不使用聚合,我使用的是简单代码,否则没有聚合就无法完成?
    • 您已经发布了正在连接的 sql 查询。如果要连接两个表,则在 mongodb 中相同,必须使用聚合。而且我认为没有其他方法(除了查找然后循环)
    • 这是我的循环代码,我知道这听起来很疯狂,但我将数字添加到数组中并且不工作 app.get("/cats", (req, res) => { Cat. find((err, doc) => { if(err) return console.log(err); doc.forEach(function(u, i) { Blog.find({"catId" : u._id}).count( function(err, count){ if(err) return console.log(err); console.log(count); u["total"] = count; console.log(u); }); console.log(u ); }) res.json(doc); }) })
    • 对不起@lhbibhbart 我不能帮你。
    • 您好,我一直在寻找相同的解决方案,发现这真的很有帮助。但是想知道是否可以使用诸如 find 之类的默认函数来完成它?我认为 Aggregate 对于大型数据集并不是那么好。
    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    相关资源
    最近更新 更多