简体   繁体   中英

mongo db with node js not able to run sum query on string object

so i have this type of documents in mongo db.

    {
        "_id" : ObjectId("599ccc896f16e74a3e26f1a9"),
        "timestamp" : ISODate("2017-08-22T17:14:59.000Z"),
        "header" : {
            "uniq_id" : "9951503422099.16801274",
            "request" : "GET /v1/api/payload"
            "username" : "user1",
            "data_length" : "201",
            "status" : "200"
        }
    },
{
        "_id" : ObjectId("599ccc896f16e74a3e26f1a9"),
        "timestamp" : ISODate("2017-08-22T17:15:59.000Z"),
        "header" : {
            "uniq_id" : "9951503422099.16801274",
            "request" : "GET /v1/api/payload"
            "username" : "user1",
            "data_length" : "301",
            "status" : "200"
        }
    }

here in the above document the data_length is in String now what i am trying to do is to group the similar types of username and add their data_length and also count the data this is what the query looks like

Model.aggregate([ {$match: {
            timestamp: {
                $gte: ISODate("2017-08-22T00:00:00.000Z"),
                $lt: ISODate("2017-08-22T23:59:00.000Z")
            }
        }},
        {
              $group: {_id: {"username": "$header.username", "request": "$header.request"},

                       response_size: {$sum :parseInt("$header.data_length")},
                       count: {$sum: 1}   
              }
        }
        ])

the result of the above query looks like this

{
    "_id" : {
        "username" : "user1",
        "request" : "GET /v1/api/payload"
    },
    "response_size" : nan,
    "count" : 2.0
}

even if putting the parseInt in data_length the result i am getting is NaN. but the response_size should come 502 how can i get the sum of data_length properly

Why don't you just change your data_length fields to type int ("data_length": 301 instead of "data_length": "301")? It appears to me your mongodb server isn't configured to allow javascript scripts - this is disabled by default and needs to be enabled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM