Reducing all documents to an array in an aggregation

user1990218 Source

I have an aggregation pipeline that returns a collection of documents like this:

{
    "_id" : {
        "ID" : "ID0001",
        "NAME" : "NAME0001"
    },
    "total_a" : 8.0,
    "total_b" : 2.0,
    "total_c" : 5.0,
    "total_d" : 5.0,
    "TOTAL" : 35.0
}

But, I would like to obtain only one document with a property inside called data with an array containing all those documents, something like this:

{
    _id: "whatever",
    aField: "aValue",
    anotherField: "anotherValue",
    data : [
        {
            "_id" : {
                "ID" : "ID0001",
                "NAME" : "NAME0001"
            },
            "total_a" : 8.0,
            "total_b" : 2.0,
            "total_c" : 5.0,
            "total_d" : 5.0,
            "TOTAL" : 20.0
        },
        {
            "_id" : {
                "ID" : "ID0002",
                "NAME" : "NAME0002"
            },
            "total_a" : 2.0,
            "total_b" : 1.0,
            "total_c" : 2.0,
            "total_d" : 5.0,
            "TOTAL" : 10.0
        }
    ]
}

I know I might be able to do that with a foreach, but, it is possible doing this inside the pipeline?

mongodbaggregation-framework

Answers

answered 3 months ago chridam #1

You would need to append another $group step to your existing aggregate pipeline where you $push the system variable $$ROOT to the data field as follows:

db.collection.aggregate([
   /* existing pipeline */
   {
       "$group": {
           "_id": null,
           "data": { "$push": "$$ROOT" },
           "aField": { "$sum": "$TOTAL" },
           "anotherField": { "$first": "anotherValue" }
       }
   }
])

$$ROOT References the top-level document currently being processed in the aggregation pipeline stage.

comments powered by Disqus