Reputation: 123
I am new to MongoDb and would appreciate some help with this query. I wrote the following aggregation pipeline
db.collection1.aggregate([
{ "$match": { "type" : "L" }},
{ "$facet": {
"ON": [
{ "$match" : {"lampStatus":'ON'}},
{ "$count": "ON" }
],
"OFF": [
{ "$match" : {"lampStatus": 'OFF'}},
{ "$count": "OFF" }
]
} },
{ "$project": {
"ON": { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ] },
"OFF": { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] },
} }
])
and got output of this type
{
"ON" : 0.0,
"OFF": 30
}
but how to get this type of output with json format
/* 1 */
{
"_id": "ON",
"count" : 0.0
}
/* 2 */
{
"_id": "OFF",
"count" : 30.0
}
any one please suggest me?
Actual Output
{
"ON" : 0.0,
"OFF" : 30
}
Expected output:
{
"_id" : "ON",
"COUNT" : 0.0
}
/* 2 */
{
"_id" : "OFF",
"COUNT" : 30.0
}
Upvotes: 0
Views: 452
Reputation: 46491
If you need some more aggregation trick
db.collection1.aggregate([
{ "$match": { "type" : "L" }},
{ "$facet": {
"ON": [{ "$match" : {"lampStatus": "ON" }}, { "$count": "ON" }],
"OFF": [{ "$match" : {"lampStatus": "OFF" }}, { "$count": "OFF" }]
}},
{ "$project": {
"ON": { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ] },
"OFF": { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] },
}},
{ "$project": {
"data": {
"$map": { "input": { "$objectToArray": "$$ROOT" }, "in": { "_id": "$$this.k", "count": "$$this.v" }}
}
}},
{ "$unwind": "$data" },
{ "$replaceRoot": { "newRoot": "$data" }}
])
Upvotes: 1
Reputation: 1581
Upodated
db.collection.aggregate([
{ "$match": { "type" : "L" }},
{ "$facet": {
"ON": [
{ "$match" : {"lampStatus":'ON'}},
{ "$count": "ON" }
],
"OFF": [
{ "$match" : {"lampStatus": 'OFF'}},
{ "$count": "OFF" }
]
} },
{"$project": {
myArray: [
{_id:"ON", count: { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ]} },
{_id:"OFF", count: { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] }}
]
}},
{"$unwind":"$myArray"},
{
"$replaceRoot": { newRoot: "$myArray" }
}
])
Upvotes: 1