首页 > 解决方案 > 使用带有条件的 $group 管道进行聚合

问题描述

这是我的数据,有 6 条记录...

      {
        _id: 1,
        entityProfiles:['company', 'provider']
      },
      {
        _id: 2,
        entityProfiles:['company']
      },
      {
        _id: 3,
        entityProfiles:['provider']
      },
      {
        _id: 4,
        entityProfiles:[]
      },
      {
        _id: 5,
        entityProfiles:null
      },
      {
        _id: 6,
      },

我需要知道总数,有多少 entityProfiles 有“提供者”,有多少没有使用 $group 和/或 $project 管道。我预料到这...

  {
    _id: 'all',
    count: 6
  },
  {
    _id: 'providers',
    count: 2
  },
  {
    _id: 'nonProviders',
    count: 4
  },

... 或这个...

  {
    _id: null,
    all: 6,
    providers: 2,
    nonProviders: 4
  },

标签: mongodbaggregation-framework

解决方案


试试这个:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      all: {
        $sum: 1
      },
      providers: {
        $sum: {
          $cond: [
            {
              $in: [
                "provider",
                {
                  $ifNull: [ "$entityProfiles", [] ]
                }
              ]
            },
            1,
            0
          ]
        }
      },
      nonProviders: {
        $sum: {
          $cond: [
            {
              $in: [
                "provider",
                {
                  $ifNull: [ "$entityProfiles", [] ]
                }
              ]
            },
            0,
            1
          ]
        }
      }
    }
  }
])

Mongo游乐场| 3个文件_id:count


推荐阅读