Я понял это.
db.people.aggregate([
{
$group: {
_id: {
country: "$country",
state: "$state",
city: "$city",
person: "$$ROOT"
}
}
},
{
$group: {
_id: {
country: "$_id.country",
state: "$_id.state",
city: "$_id.city",
person: "$_id.person"
},
people: {
$push: "$_id.person"
}
}
},
{
$group: {
_id: {
country: "$_id.country",
state: "$_id.state"
},
cities: {
$push: {
city: "$_id.city",
people: "$people"
}
}
}
},
{
$group: {
_id: {
country: "$_id.country"
},
states: {
$push: {
state: "$_id.state",
cities: "$cities"
}
}
}
},
{
$project: {
_id: 0,
country: "$_id.country",
states: "$states"
}
}
]);
Результат будет выглядеть так:
{
"country": "US",
"states": [
{
"state": "NY",
"cities": [
{
"city": "New York City",
"people": [
{
"_id": "5cd80e1ab3ee820fd9416301",
"name": "John Doe",
"city": "New York City",
"state": "NY",
"country": "US"
}
]
}
]
}
]
}