【问题标题】:how can i count all users and posts in mongoDB我如何计算 mongoDB 中的所有用户和帖子
【发布时间】:2021-10-27 05:18:42
【问题描述】:

我想统计网站的用户、帖子和 cmets,并将数据发送到仪表板,仪表板显示所有用户和帖子的计数。我无法解决这个问题。这是我的代码

     app.get('/', async (req,res)=>{
       const query = User.find()
       const posts = Post.find()
      const user = await query.countDocuments((err,count)=>{
           if(err){
               console.log(err)
           }else{
               return count;
           }
       })
   const post = await posts.countDocuments((err , posts)=>{
    if(err){
        console.log(err)
    }else{
        return posts;
    }
   })
console.log(post)
   res.render('dashboard',{userCount: user , posts:post})

})

【问题讨论】:

    标签: node.js mongoose ejs


    【解决方案1】:

    您可以使用聚合找到文档的数量:

    const postCount = await posts.aggregate([{$group: {
      _id : null,
      count : { $sum : 1}
    }}, {$project: {
      _id : 0
    }}]);
    

    你会得到如下输出: count : 11

    说明

    $group 阶段将选择不同的记录。当设置为 null 时,它会选择集合中的所有记录。

    $projectstage 将选择我们需要输出的字段(由于我们只需要计数,因此可以消除其他字段)

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多