Hi Ronald,
Let's say the data looks like this (expanding the example docs with a made up field):
{
"city": "NEW YORK",
"state": "NY",
"pop": 5574,
"party": "democrat"
}
and I would like to make queries such as "for a given party, return the state with the highest population", so:
{ $match: {party: "democrat"}},
{ $sort: {pop: -1} },
What I would then like to get back would be the full documents organised by state. I currently do this using the following explicit $group
{
$group:
{
_id: "$state",
result:
{
city: {$first: "$city"},
state: {$first: "$state"},
pop: {$first: "$pop"},
party: {$first: "$party"}
}
}
}
but this seems overly verbose (especially when my documents are more complicated). Is there a way to write an equivalent query which doesn't involve explicitly writing every field? Something as terse as this would be perfect:
{ $group: { _id: "$state", result: $first }}
which would also allow the query to return more details, such as
{ $group: { _id: "$state", highest: $first, lowest: $last}}
--
Sam
Ronald Stalder wrote:
>
> I'm not sure I understand what you mean by "first entry of each group". Aggregate returns you one array element per group.
>