printing data other than $group in mongo using aggregation frame work

27 views
Skip to first unread message

shankar gandhi

unread,
Apr 24, 2016, 12:28:35 PM4/24/16
to mongodb-user
I am trying to print data apart from fields used in $group but didn't found any way.

for e.g my query is 

     db.test.aggregation({"$project": "status":1,"cost":1 },{"$group":{_id: "name","cost"}})

it will print only "cost" not "status". Let me know hot to do it in mongo

Rhys Campbell

unread,
Apr 25, 2016, 3:18:50 AM4/25/16
to mongodb-user
Provide a few sample documents.

Amar Singh

unread,
Apr 26, 2016, 8:35:08 AM4/26/16
to mongod...@googlegroups.com
By default $group gives only the the grouped field value. You can use $first, $last, $push for getting other fields.

One example could be like this

db.test.aggregation({"$project": "status":1,"cost":1 },{"$group":{_id: "name","cost"},"status":{"$first":"$status"}})

You can use other operators as well.


Amar Singh

On Mon, Apr 25, 2016 at 12:48 PM, Rhys Campbell <rhys.jame...@gmail.com> wrote:
Provide a few sample documents.

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.org/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/71cbb709-588b-4d29-b31f-f69168a26110%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Asya Kamsky

unread,
Apr 27, 2016, 4:58:58 PM4/27/16
to mongodb-user
Amar is right, but I would add to that that you should remove the
$project stage.

Your $project stage is not doing anything useful so it's going to slow
down performance of the pipeline. Aggregation already examines the
pipeline to see which fields it needs to output the final result so
using $project to "prune down" the fields is counter-productive.

Asya
> https://groups.google.com/d/msgid/mongodb-user/CAA1QGCCbSAuUrMcfDRmbU7tHuW-pd8YY%2B3s%2BRWzQ9BZXf%3DU_5g%40mail.gmail.com.
>
> For more options, visit https://groups.google.com/d/optout.



--
Asya Kamsky
Lead Product Manager
MongoDB
Download MongoDB - mongodb.org/downloads
Free MongoDB Monitoring - cloud.mongodb.com
Free Online Education - university.mongodb.com
Get Involved - mongodb.org/community
We're Hiring! - https://www.mongodb.com/careers
Reply all
Reply to author
Forward
0 new messages