$addFields when no $match found

前端 未结 1 723
走了就别回头了
走了就别回头了 2020-12-07 05:17

Iam new Mongodb developer i wrote mongodb aggregation.one of my field lampStatus : \"OFF\" is 30 recors are there iam using \"{ $match: {lampStatus : \"OFF\"}}\"i got 30 rec

相关标签:
1条回答
  • 2020-12-07 05:47

    You can somewhat ridiculously do this with $facet and $ifNull aggregation

    db.collection.aggregate([
      { "$facet": {
        "array": [
          { "$match": { "type": "L", "lampStatus": "ON" }},
          { "$group": {
            "_id": null,
            "TotalLights": { "$sum": 1 }
          }},
          { "$project": { "_id": 0, "TotalLights": 1 }}
        ]
      }},
      { "$project": {
        "TotalLights": {
          "$ifNull": [{ "$arrayElemAt": ["$array.TotalLights", 0] }, 0 ]
        }
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题