chmiga092020
chmiga092020

Reputation: 21

Mongodb Aggregation Query Example

I was hoping someone could help me with a question. I have data that show population by zip codes. the data also includes city, location, and sate. I am wanted to aggregate the data to show the city with the highest population per state. Please see below of my first attempt. I was hoping to aggregate by state and city to summarize the population(there were multiple zip codes in the same city). After that I was hoping then to find the highest populated city by state. After this I was trying to $slice the document id but it was considered as an object instead of an array.

db.getCollection("codes").aggregate(
[
    { 
        "$group" : { 
            "_id" : { 
                "state" : "$state", 
                "city" : "$city"
            }, 
            "population" : { 
                "$sum" : "$pop"
            }
        }
    }
], 
{ 
    "allowDiskUse" : false
});

Here is how some of the data looks:

{ 
"_id" : "01035", 
"city" : "HADLEY", 
"loc" : [
    -72.571499, 
    42.36062
], 
"pop" : NumberInt(4231), 
"state" : "MA"}

The final output should look something like this

final output format

Upvotes: 0

Views: 876

Answers (1)

Cássio Lacerda
Cássio Lacerda

Reputation: 1634

  1. Sort cities by pop descending order, and then;
  2. Group by state and get the first city name and population;
db.collection.aggregate([
  {
    $sort: {
      pop: -1
    }
  },
  {
    $group: {
      _id: "$state",
      city: {
        $first: "$city"
      },
      population: {
        $first: "$pop"
      }
    }
  }
])

You can see working example in MongoDB playground.

Upvotes: 1

Related Questions