Multiple Counts with single query in mongodb

前端 未结 3 770
被撕碎了的回忆
被撕碎了的回忆 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:03

    You can try below $facet aggregation

    $count aggregation will always give you the counts for only single matching ($match) condition. So you need to further divide your each count into multiple section and that's what the $facet provides by processes multiple aggregation pipelines within a single stage on the same set of input documents.

    db.collection.aggregate([
      { "$facet": {
        "Total": [
          { "$match" : { "ReleaseDate": { "$exists": true }}},
          { "$count": "Total" },
        ],
        "Released": [
          { "$match" : {"ReleaseDate": { "$exists": true, "$nin": [""] }}},
          { "$count": "Released" }
        ],
        "Unreleased": [
          { "$match" : {"ReleaseDate": { "$exists": true, "$in": [""] }}},
          { "$count": "Unreleased" }
        ]
      }},
      { "$project": {
        "Total": { "$arrayElemAt": ["$Total.Total", 0] },
        "Released": { "$arrayElemAt": ["$Released.Released", 0] },
        "Unreleased": { "$arrayElemAt": ["$Unreleased.Unreleased", 0] }
      }}
    ])
    

    Output

    [{
        "Total": 3,
        "Released": 2,
        "Unreleased": 1
    }]
    

提交回复
热议问题