MongoDB facet subpipeline array filter with condition

69 Views Asked by At

I have aggregation with query as https://mongoplayground.net/p/jxaI7MAyBmJ

I have project type, count and empName by adding stages under data to filter with below 2 condition

  1. type as a2 and
  2. empName (type as a1) should need to equal with empName (type as a2).
db.collection.aggregate([
  {
    $facet: {
      "data": [
        {
          $match: {
            type: {
              $in: [
                "a1",
                "a2"
              ]
            }
          }
        },
        {
          $group: {
            _id: {
              emp_name: "$emp_name",
              type: "$type"
            },
            count: {
              $sum: 1
            }
          }
        },
        {
          $project: {
            empName: "$_id.emp_name",
            type: "$_id.type",
            count: 1,
            _id: 0
          }
        }
        
        //Have to ADD sub stages here with the above mentioned 2 condition
      ]
    }
  }
])

I tried on applying this condition however unable to resolve this.

Thanks in advance

1

There are 1 best solutions below

2
Wernfried Domscheit On

I still don't understand what you are looking for, but this one gives the desired result:

db.collection.aggregate([
   { $match: { type: { $in: ["a1", "a2"] } } },
   {
      $facet: {
         a1: [
            { $match: { type: "a1" } },
            { $project: { _id: 0, emp_name: 1 } }
         ],
         a2: [
            { $match: { type: "a2" } }
         ],
      }
   },
   { $unwind: "$a2" },
   { $match: { $expr: { $in: ["$a2.emp_name", "$a1.emp_name"] } } },
   {
      $group: {
         _id: "$a2.emp_name",
         count: { $count: {} },
      }
   },
   {
      $project: {
         _id: 0,
         type: "a2",
         count: 1,
         empName: "$_id"
      }
   }
])

Mongo Playground