group in mongo excluding null values

前端 未结 3 2047
-上瘾入骨i
-上瘾入骨i 2021-01-17 10:58

I have mongo query which does the group operation on the documents.

I have almost got the expected results except that I want to refine the results without empty or

3条回答
  •  礼貌的吻别
    2021-01-17 11:33

    this example includes two different Collections. For this we use aggregate function. I am also using Mongoose

    1. I am joining the cusmtomfield with customfiellabels with $lookup
    2. Flat the array with $unwind
    3. $match to exclude the name that have INACTIVE in the text (I'm using REGEX)
    4. $project to rename the Fields to show properly on the client

      . async getAllMasterDataCustomFields(req) {

          let response = {};
          try {
      
            response = await customfieldsModel.aggregate([
              {
                $lookup: {
                  from: 'customfieldlabels',
                  localField: 'cfId',
                  foreignField: 'cfId',
                  as: 'info'
                }
              },
              { '$unwind': { 'path': '$info', 'preserveNullAndEmptyArrays': true } },
              { '$match': { 'childs.name': { $not: /INACTIVE/ }}},
              {
                $project: {
                  'cfId': 1,
                  'label': '$info.label',
                  'type': '$info.type',
                  'childs': 1
                }
              }]).exec();
      
          } catch (e) {
            logger.log('error', `Error while getting response ${e.meesage}`);
          }
      
          return response;
        }
      

      .

提交回复
热议问题