MongoDB聚合查询组的按和计数

时间:2019-03-03 20:38:41

标签: mongodb aggregate-functions

我有一个订户集合:

 {id: ObjectId ('52dskf45f10dsd4775'), agencyCode: '4579520',
        listOfSubscriptions: [
        {name: 'william', CreatedAt: ISODate ('2019-01-02'), subscriptionType: 'smartphones'},
        {name: 'marianna', CreatedAt: ISODate ('2019-02-02'), subscriptionType: 'smartphones'},
        {name: 'Freewind', CreatedAt: ISODate ('2019-04-02'), subscriptionType: 'smartphones'}
       ]
 }

代理商集合包含以下数据:

{agencyCode: '4579520', BU: 'finances', company: ObjectId (' 445700500b24dsjdfm ')}
{agencyCode: '45007', BU: 'finances', company: ObjectId (' 445700500b24dsjdfm ')}

收藏订阅类型:

 {id:ObjectId ('5lkf81gf45005drkj') ,nameSubscription: 'intense',SubscriptionType: 'smartphones' }
 {id:ObjectId ('eb4512ezope780') ,nameSubscription: 'other',SubscriptionType: 'other' }

我想按订阅类型对订阅者进行竞争。

这是我的请求mongodb:

 subscribers.aggregate(
    [
    {
        $lookup: {
          from: "agencys",
          localField: "agencyCode",
          foreignField: "agencyCode",
          as: "data_agency"
        }
      },
      { $unwind: "$data_agency" },
      { $unwind: "$listOfSubscriptions" },
      {
        $match: {
          $and: [
            { $agencyCode: '4579520' },
            { "data_agency.BU": 'finances' },
            { "data_agency.company": mongoose.Types.ObjectId('445700500b24dsjdfm') },

          ]
        }
      },
      {
        $group: {
          "_id": "$listOfSubscriptions.subscriptionType",
          countLines: { $sum: 1 },
        }
      },
]

我的请求结果:

 {
    "_id": "smartphones",
     "countLines": 3
  }

我的请求结果未显示其余的订阅类型。 我要显示代理商'4579520'的所有此类订阅类型:

{
    "_id": "smartphones",
     "countLines": 3
  },
{
    "_id": "other",
     "countLines": 0
  }

谢谢

0 个答案:

没有答案
相关问题