[SERVER-45333] Why we can not push not push the data from top in $group aggreagtion Created: 02/Jan/20  Updated: 06/Jan/20  Resolved: 06/Jan/20

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: 4.3.2
Fix Version/s: None

Type: Question Priority: Major - P3
Reporter: Saubhik Singh Assignee: Eric Sedor
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates SERVER-24799 $group aggregation command should mai... Closed
Participants:

 Description   

 

data = [
{"name": a, dept: "IT", score: 150},
{"name": b, dept: "IT", score: 100},
{"name": c, dept: "Sales", score: 260},
{"name": d, dept: "Sales", score: 200}
]

Now we run following aggregation

 

 

db.serviceoffering.aggregate([
    {$sort: {score: 1}},
    {$group: {_id: {dept: "$dept"}, user: {$push: "$$ROOT"}}}
])

 

Now after $sort pipeline the result would be following:

 

 

data = [
{"name": b, dept: "IT", score: 100},
{"name": a, dept: "IT", score: 150},
{"name": d, dept: "Sales", score: 200},
{"name": c, dept: "Sales", score: 260}
]

 

But after $group pipeline result becomes:

{
{
_id: IT,
user:[
  {"name": d, dept: "Sales", score: 200}, 
  {"name": c, dept: "Sales", score: 260} 
]
},
{
_id: Sales,
user:
  [
    {"name": b, dept: "IT", score: 100}, 
    {"name": a, dept: "IT", score: 150}
  ]
}
}

If you observe the result data has been taken from bottom and hence even after sort d,c are on top in the final result.

 



 Comments   
Comment by Saubhik Singh [ 06/Jan/20 ]

Thanks for your input, Eric Sedor.

Comment by Eric Sedor [ 03/Jan/20 ]

saubhik.singh@gslab.com, $group does not order its output documents so you can't expect the output of $group to agree with a previous $sort stage. You can specify an additional $sort stage to enforce order after the $group.

For further questions about how to use the aggregation framework I encourage you to ask our community by posting on the mongodb-user group or on Stack Overflow with the mongodb tag. The primary purposes of the SERVER project are bug reports and feature requests.

Sincerely,
Eric

Generated at Thu Feb 08 05:08:30 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.