3

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?

0

1 Answer 1

13

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.