How to change MongoDB output JSON format

Naresh

New Member
#1
I am new to MongoDb and would appreciate some help with this query. I wrote the following aggregation pipeline
Mã:
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
Mã:
{
    "ON" : 0.0,
    "OFF": 30
}
but how to get this type of output with json format
Mã:
/* 1 */
{
    "_id": "ON",
    "count" : 0.0
}

/* 2 */
{
    "_id": "OFF",
    "count" : 30.0
}
any one please suggest me?
Actual Output
Mã:
{
    "ON" : 0.0,
    "OFF" : 30
}
Expected output:
Mã:
{
    "_id" : "ON",
    "COUNT" : 0.0
}

/* 2 */
{
    "_id" : "OFF",
    "COUNT" : 30.0
}
 

Admin

Administrator
Thành viên BQT
#2
Because the $count operator is the equivalent to the following $group + $project sequence:
Mã:
db.collection.aggregate( [
   { $group: { _id: null, myCount: { $sum: 1 } } },
   { $project: { _id: 0 } }
])
You can re-write your pipeline to use the $group stage for getting the counts as
Mã:
Model.aggregate([
    { "$match": { "type" : "L" }},
    { "$group": {
        "_id": "$lampStatus",
        "COUNT": { "$sum": 1 }
    } }
]).exec((err, results) => console.log(results))
For getting the exact output, add extra $objectToArray and $replaceRoot pipelines as follows:
Mã:
Model.aggregate([
    { "$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": {
        "counts": {
            "$map": {
                "input": { "$objectToArray": "$$ROOT" },
                "as": "el",
                "in": {
                    "_id": "$$el.k",
                    "COUNT": "$$el.v"
                }
            }
        }
    } },
    { "$unwind": "$counts" },
    { "$replaceRoot": { "newRoot": "$counts" } }
]).exec((err, results) => console.log(results))
 
OP
OP
N

Naresh

New Member
#3
this code almost done but small issue lampStatus:"OFF"there is 30 records i got { "_id" : "OFF", "COUNT" : 30.0 }but lampStatus:"ON there is no records but i want "{ "_id" : "ON", "COUNT" : 0.0 }this is my requirement
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Chủ Đề Xem Nhiều

Top