micheangelo
micheangelo

Reputation: 33

MongoDB- arrays from aggregation result

I have the following MongoDB query:

db.my_collection.aggregate([
{
    $group: {"_id":"$day", count: { $sum: "$myValue" }
}}])

It returns the following result:

{
    "_id" : ISODate("2020-02-10T00:00:00.000+01:00"),
    "count" : 10
},
{
    "_id" : ISODate("2020-02-01T00:00:00.000+01:00"),
    "count" : 2
}

Is it possible to make two arrays from this result as below?

 {
    "days": [ISODate("2020-02-10T00:00:00.000+01:00"), ISODate("2020-02-01T00:00:00.000+01:00")],
    "values": [10, 2]
 }

Upvotes: 1

Views: 37

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

Yes, just add another $group stage:

db.my_collection.aggregate([
    {
        $group: {
            "_id": "$day", count: {$sum: "$myValue"}
        }
    },
    {
        $group: {
            "_id": null,
            days: {$push: "$_id"},
            values: {$push: "$count"}
        }
    }
])

Upvotes: 2

Related Questions