【问题标题】:Mongodb aggregation in Nodejs and express jsNodejs和express js中的mongodb聚合
【发布时间】:2020-06-05 16:16:45
【问题描述】:

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

我目前正在寻找在Node js 中执行Aggregation 的方法。

下面是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.js mongodb express


    【解决方案1】:

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

    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)
    })
    
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多