未找到 $match 时的 $addFields [英] $addFields when no $match found

查看:15
本文介绍了未找到 $match 时的 $addFields的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的 Mongodb 开发人员,我编写了 mongodb 聚合.我的字段 lampStatus 之一:OFF"是 30 个记录,我使用{ $match: {lampStatus:OFF"}}"我得到了 30 条记录但是'lampStatus:"OFF" '没有记录我正在获取 0 条记录,但如何在上述聚合中获取零值.

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




              ])

输出:在 0 毫秒内获取了 0 条记录

output:Fetched 0 record(s) in 0ms

expected outout:"TotalLights" : 0

推荐答案

你可以用 $facet$ifNull 聚合

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

这篇关于未找到 $match 时的 $addFields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆