如何使用MongoDb聚合获得不匹配的记录值

问题描述 投票:1回答:1

我是Mongo Db的新手,并希望对这个查询有所帮助。我写了mongodb聚合我的字段“lampStatus”:'OFF'是30条记录在那里和“lampStatus”:'ON'是没有记录在那里我出去了放{{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] }
  }},

])

输出:{“OFF”:30}

expected ouput:{
  "OFF" : 30,
  "ON":0
 }
mongodb mongoose mongodb-query aggregation-framework
1个回答
1
投票

你需要使用$ifNull$project这样的舞台

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

你会得到

[{
  "OFF": 30,
  "ON": 0
}]
© www.soinside.com 2019 - 2024. All rights reserved.