CobaltBabyBear
CobaltBabyBear

Reputation: 2218

MongoDB: Create Object in Aggregation result

I want to return Object as a field in my Aggregation result similar to the solution in this question. However in the solution mentioned above, the Aggregation results in an Array of Objects with just one item in that array, not a standalone Object. For example, a query like the following with a $push operation

 $group:{
     _id: "$publisherId",
     'values' : { $push:{
         newCount: { $sum: "$newField" },
         oldCount: { $sum: "$oldField" } }
     }
}

returns a result like this

{
        "_id" : 2,
        "values" : [ 
            {
                "newCount" : 100, 
                "oldCount" : 200
            }
        ]
    }
}

not one like this

{
        "_id" : 2,
        "values" : {
                "newCount" : 100, 
                "oldCount" : 200
         }
    }
}

The latter is the result that I require. So how do I rewrite the query to get a result like that? Is it possible or is the former result the best I can get?

Upvotes: 3

Views: 11434

Answers (1)

chridam
chridam

Reputation: 103365

You don't need the $push operator, just add a final $project pipeline that will create the embedded document. Follow this guideline:

var pipeline = [
    {
        "$group": {
            "_id": "$publisherId",      
            "newCount": { "$sum": "$newField" },
            "oldCount": { "$sum": "$oldField" } 
        }
    },
    {
        "$project" {
            "values": {
                "newCount": "$newCount",
                "oldCount": "$oldCount"
            }
        }       
    }   
];

db.collection.aggregate(pipeline);

Upvotes: 13

Related Questions