user4434001
user4434001

Reputation:

How sum a field in a database

I'm trying to group all fields with the same event name, and sum the participants of this fields.

{
    "_id": {
        "$oid": "54b6ae8aec17b5e905a5813a"
    },
    "person": {
        "name": "Something",
        "phone": "(011) 9468-1319",
        "email": "[email protected]",
        "obs": ""
    },
    "event": {
        "full": "20/11/01 Classic",
        "date": "20/11/01",
        "name": "Special",
        "participants": 10
    },
    "__v": 0
}
{
    "_id": {
        "$oid": "54b6aeaad7e410ec05dd1ca2"
    },
    "person": {
        "name": "Something",
        "phone": "(011) 9468-1319",
        "email": "[email protected]",
        "obs": ""
    },
    "event": {
        "full": "20/11/01 Classic",
        "date": "20/11/01",
        "name": "Special",
        "participants": 10
    },
    "__v": 0
}

I have just this two collections, and i am using the following code to a group by the event.full and them sum the participans (Number) field.

This is the code:

MyModel.aggregate(
    [
        { "$group": 
            { 
                _id: "$event.full",
                participants: { "$sum": "$participants" },
                count: { $sum: 1 }
            } 
        },
        { "$skip": ( page-1 ) * 15 },
        { "$limit": 15 }
    ],
    function(err, obj) {
        res.send(obj);
    }
);

This is returning the following object:

[
 {
  _id: "20/11/01 Classic",
  participants: 0,
  count: 2
 }
]

Why the sum field is not working? How fix??

Upvotes: 1

Views: 78

Answers (1)

Disposer
Disposer

Reputation: 6371

you missed the event use this:

[
        { "$group": 
            { 
                _id: "$event.full",
                participants: { "$sum": "$event.participants" },
                count: { $sum: 1 }
            } 
        },
        { "$skip": ( page-1 ) * 15 },
        { "$limit": 15 }
 ]

Upvotes: 2

Related Questions