Multiple Counts with single query in mongodb

前端 未结 3 786
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 07:35

I am new to Mongo Db and would appreciate some help with this query. I have been sifting through posts here for the past couple of days tearing my hair to see if I could fin

3条回答
  •  忘掉有多难
    2020-11-27 08:04

    You can use below aggregation.

    $gt > null - to check whether field exists or not in aggregation expressions.

    $cond with $sum to output 0 and 1 based on release date filter.

    $add to add both released and unreleased count to output total.

    db.Movies.aggregate([
     {"$group":{
       "_id":null,
       "Unreleased":{"$sum":{"$cond":[{"$and":[{"$gt":["$ReleaseDate",null]},{"$ne":["$ReleaseDate",""]}]},0,1]}},
       "Released":{"$sum":{"$cond":[{"$and":[{"$gt":["$ReleaseDate",null]},{"$ne":["$ReleaseDate",""]}]},1,0]}}
     }},
     {"$addFields":{"Total":{"$add":["$Unreleased","$Released"]}}}
    ])
    

提交回复
热议问题