Naresh Varun Guttula
Naresh Varun Guttula

Reputation: 123

how to change MongoDB output JSON format

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

Answers (2)

Ashh
Ashh

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

abdul
abdul

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

Related Questions