首页 > 解决方案 > 如何在mongoDB中获取记录计数分组字段值?

问题描述

我想按组字段(国家/地区)值获取记录总数,我正在尝试但没有得到它。下面是我的代码:-

var company_id= company._id
 FollowCompany.aggregate(
      [   
          {
            $match: { company_id :company_id }  // company_id field in database and user param
          },
          {
              $group:
              {
                  _id: "$country" ,   // need to group by country in database
                  count: { $sum:1 },

              }
          },
          { $sort : { entry_date : -1 } },
      ]).exec(function(err, followerData) {
        console.log(followerData)

      })

它显示空结果,有什么帮助或想法吗?提前致谢

标签: mongodbgroup-bymongodb-query

解决方案


我找到了解决方案,现在我想将 _id 字段显示为国家/地区,任何解决方案,下面是我的代码:

 FollowCompany.aggregate(
      [   
          {
            $match: {company_id:""+company_id+""}
          },
          {
              $group:
              {
                  _id: "$country" , 
                  count: { $sum:1 },

              }
          },
          { $sort : { _id : 1 } },
      ])

输出是

 {
        "_id": "India",
        "count": 1
    }

我想要这样

 {
        "country": "India",
        "count": 1
    }

推荐阅读