Home > database >  mongo group by sum not working in same cases
mongo group by sum not working in same cases

Time:03-08

I have 2 queries:

aggregate( [
  { 
      $match: {"user_id": 5918725, "shop_id": 1775207, "$text": {"$search" : "API"}}
  },
  { 
      $group: { 
          _id: "_id", 
          count: { 
              $sum: { 
                  $cond: [ { $eq: [ "$deleted_at", null ] }, 1, 0 ]  
              } 
          } 
      } 
  }
]);

and

aggregate( [
  { 
      $match: {"user_id": 5918725, "shop_id": 1775207, "$text": {"$search" : "APIU"}}
  },
  { 
      $group: { 
          _id: "_id", 
          count: { 
              $sum: { 
                  $cond: [ { $eq: [ "$deleted_at", null ] }, 1, 0 ]  
              } 
          } 
      } 
  }
]);

they are the same, only difference is a search keyword, but they behave differently, in case of the first query, result is :

{
    "_id" : null,
    "count" : 0.0
}

which is expected result, but in case of the second one, result is Fetched 0 record(s) (that is what my GUI shows). So for some reason in case of the second query it simply ignore group/sum and trying to get actual records. How can I solve it, thank you in advance!

CodePudding user response:

Query

  • the easy way to do it its on the driver, if no results you make this document with code
  • this is the way to do it on the database, with 2 extra stages, union and group, and one extra collection (in mongodb 5.3 we wouldnt need the extra collection)
  • put for example instead of 5 a negative number and even if no results you still get count : 0

Test code here

aggregate(
[{"$match":{"$expr":{"$lt":["$a", 5]}}},
 {"$group":{"_id":null, "count":{"$sum":1}}},
 {"$unionWith":{"coll":"2"}},
 {"$group":{"_id":null, "count":{"$sum":"$count"}}}])
  • Related