Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-shell

How to change the mongod db query to aggregation


  1. I have three queries and now I want to change this to MongoDB aggregation and below is the code:

          db.mycollection.count({$and:[$requestB:{$exists:false},[$requestC:{$exists:false}]})
          db.mycollection.count({requestB:{$exists:true}})
          db.mycollection.count({requestC:{$exists:true}})
    
  2. Now i want to change this code to aggregation but it did not work

       db.mycollection.aggregate( [
     { $group: {
         '_id' : { user_id: '$user_id'},
         requestA_count: { $sum: {
             $cond: [ {$and: [{$eq: ["$requestB", null]}, {$eq: ["requestC", null]}}}, 1, 0 ]
         } },
         requestB_count: { $sum: {
             $cond: [ {requestB:{'$exists':true}}, 1, 0 ]
         } },
         requestC_count: { $sum: {
             $cond: [ {requestC:{'$exists':true}}, 1, 0 ]
         } },
     } },
     { $project: {
         _id: 0,
         user_id: '$_id.user_id',
         requestA_count: 1,
         requestB_count: 1,
         requestC_count: 1
     } }
     ] );
    

Solution

  • You can use $type instead of $exists inside $group,

    db.collection.aggregate([
      {
        $group: {
          "_id": { user_id: "$user_id" },
          requestA_count: {
            $sum: {
              $cond: [
                {
                  $and: [
                    { $ne: [{$type: "$requestA"}, "missing"] }, 
                    { $eq: [{$type: "$requestB"}, "missing"] }, 
                    { $eq: [{$type: "$requestC"}, "missing"] }
                  ]
                },  // you need to close bracket here not below
                1, 0
              ]
            }
          },
          requestB_count: {
            $sum: { $cond: [{ $ne: [{ $type: "$requestB" }, "missing"] }, 1, 0] }
          },
          requestC_count: {
            $sum: { $cond: [{ $ne: [ { $type: "$requestC" }, "missing" ] }, 1, 0] }
          }
        }
      },
      {
        $project: {
          _id: 0,
          user_id: "$_id.user_id",
          requestA_count: 1,
          requestB_count: 1,
          requestC_count: 1
        }
      }
    ])
    

    Playground