Naresh Varun Guttula
Naresh Varun Guttula

Reputation: 123

How to get non matched records value with MongoDb aggregation

I am new to Mongo Db and would appreciate some help with this query.I wrote mongodb aggregation one my field "lampStatus": 'OFF' is 30 records are there and "lampStatus": 'ON' is no records are there i got out put {"OFF" : 30} i have not getting {"ON" : 0} value please any one suggest me.

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

])

output:{ "OFF" : 30 }

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

Upvotes: 1

Views: 166

Answers (1)

Ashh
Ashh

Reputation: 46461

You need to use $ifNull with the $project stage something like this

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

You will get

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

Upvotes: 1

Related Questions