$addFields when no $match found

好久不见. 提交于 2019-12-17 21:12:24

问题


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 records but ' lampStatus : "OFF" 'there is no records iam getting Fetched 0 record(s) but how to get zero value in the above aggergation.

db.collection.aggregate([

                  { $match:{'type':'L'}},
                  { $match: {lampStatus : "ON"}},
                  { $group: { _id : null, TotalLights: { $sum: 1 } } },
                  { $project: { _id: 0, TotalLights: 1 } }




              ])

output:Fetched 0 record(s) in 0ms

expected outout:"TotalLights" : 0

回答1:


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 ]
    }
  }}
])


来源:https://stackoverflow.com/questions/52071636/addfields-when-no-match-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!