【问题标题】:How to get non matched records value with MongoDb aggregation如何使用 MongoDb 聚合获取不匹配的记录值
【发布时间】:2019-02-05 02:47:53
【问题描述】:

我是 Mongo Db 的新手,希望对这个查询有所帮助。我写了 mongodb 聚合一个我的字段 "lampStatus": 'OFF' is 30 records are there and "lampStatus": 'ON' is no records are there我出来了 {"OFF" : 30} 我没有得到 {"ON" : 0} 值请任何人建议我。

 db.collection.aggregate([
  { $match:{"type" : "L"}},
  { "$facet": {
    "ON": [
      { "$match" : {"lampStatus":'ON'}},
      { "$count": "ON" }
    ],
    "OFF": [
      { "$match" : {"lampStatus": 'OFF'}},
      { "$count": "OFF" }
    ]
  }},
  { "$project": {
    "ON": { "$arrayElemAt": ["$ON.ON", 0] },
    "OFF": { "$arrayElemAt": ["$OFF.OFF", 0] }
  }},

])

输出:{ “关”:30 }

expected ouput:{
  "OFF" : 30,
  "ON":0
 }

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您需要将$ifNull$project 舞台类似

    { "$project": {
      "ON": { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ] },
      "OFF": { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] }
    }}
    

    你会得到

    [{
      "OFF": 30,
      "ON": 0
    }]
    

    【讨论】:

    • 非常感谢安东尼。这解决了我的问题。非常感谢@Anthony Winzlet 的帮助
    • 嗨 Anthony Winzlet 任何可能的这种 json 格式输出 { "_id" : "ON", "count" : 0.0 } /* 2 */ { "_id" : "OFF", "count " : 30.0 } @Anthony Winzlet
    猜你喜欢
    • 2021-08-08
    • 2013-12-19
    • 2020-10-13
    • 2019-06-19
    • 2021-07-28
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多