首页 > 解决方案 > Nodejs和express js中的mongodb聚合

问题描述

下面的聚合在 mongo db 中工作,但是当我尝试将它与节点 js 集成以获取计数值时API,它返回 null 值

我目前正在寻找AggregationNode js.

下面是与node js的集成代码

   app.get('/count', (req, res) => {
      var name = req.params.name;

      adpostdata.aggregate([
        { "$facet": {
          "Total": [
            { "$match" : { "category": { "$exists": true }}},
            { "$count": "Total" },
          ]
        }},
        { "$project": {
          "Total": { "$arrayElemAt": ["$Total.Total", 0] },
        }}
      ], (err, result) => {
        if (err) return console.log(err)
        console.log(result)
       res.send(result+"")
    })

      })

我的输入是

{
category :"dress"
}
{
category:"cars" 
}

标签: node.jsmongodbexpress

解决方案


谢谢大家的帮助,现在我可以得到我的例外输出了

app.get('/count', (req, res) => {

  adpostdata.aggregate(
    [
      // Count the number of books published in a given year
      {
        $facet: {
          "categories": [
      {
        $group: {
          _id: '$category',
          count: { $sum: 1 }
        }
      },
      // Sort by year descending
      { $sort: { count: -1, _id: -1 } }
    ],

    "Total": [
      { "$match" : { "category": { "$exists": true }}},
      { "$count": "Total" },
    ],


  }}]).toArray( (err, result) => {
    if (err) return console.log(err)
    console.log(result)
   res.send(result)
})

  })

推荐阅读