Created
          December 27, 2018 02:07 
        
      - 
      
- 
        Save tabvn/dfd2137db7577e004f28f8899b7c31c2 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | const query = [ | |
| { | |
| $lookup: { | |
| localField: '_id', | |
| foreignField: 'productionId', | |
| from: 'production_lead', | |
| as: 'production_lead' | |
| } | |
| }, | |
| { | |
| $unwind: { | |
| path: '$production_lead', | |
| preserveNullAndEmptyArrays: true, | |
| } | |
| }, | |
| // join staff | |
| { | |
| $lookup: { | |
| localField: 'production_lead.staffId', | |
| foreignField: '_id', | |
| from: 'staff', | |
| as: 'staff' | |
| } | |
| }, | |
| { | |
| $unwind: { | |
| path: '$staff', | |
| preserveNullAndEmptyArrays: true, | |
| } | |
| }, | |
| //join freelancer | |
| { | |
| $lookup: { | |
| localField: 'production_lead.freelancerId', | |
| foreignField: '_id', | |
| from: 'freelancer', | |
| as: 'freelancer' | |
| } | |
| }, | |
| { | |
| $unwind: { | |
| path: '$freelancer', | |
| preserveNullAndEmptyArrays: true, | |
| } | |
| }, | |
| { | |
| $match: matchQuery, | |
| }, | |
| { | |
| $match: { | |
| $and: [ | |
| { | |
| 'revenue': {$exists: true,} | |
| }, | |
| { | |
| 'revenue': {$ne: null} | |
| }, | |
| { | |
| 'revenue': {$gt: 0,} | |
| } | |
| ], | |
| } | |
| }, | |
| { | |
| $group: { | |
| _id: '$_id', | |
| revenue: {$first: '$revenue'}, | |
| staff: {$first: '$staff'}, | |
| freelancer: {$first: '$freelancer'}, | |
| } | |
| }, | |
| { | |
| $project: { | |
| _id: false, | |
| revenue: true, | |
| lead: { | |
| $cond: {if: {$ne: ['$staff', null]}, then: '$staff', else: '$freelancer'} | |
| } | |
| }, | |
| }, | |
| { | |
| $project: { | |
| revenue: true, | |
| lead: { | |
| _id: '$lead._id', | |
| firstName: '$lead.firstName', | |
| lastName: '$lead.lastName', | |
| } | |
| } | |
| }, | |
| { | |
| $group: { | |
| _id: '$lead._id', | |
| lead: {$first: '$lead'}, | |
| revenue: {$sum: '$revenue'}, | |
| } | |
| }, | |
| { | |
| $sort: { | |
| 'revenue': -1 | |
| } | |
| }, | |
| { | |
| $limit: 10 | |
| } | |
| ] | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment