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

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

问题描述

我是Mongodb的新开发人员,我写了mongodb Aggregation.one我的field 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 聚合

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天全站免登陆