Home > database >  NOSQL MONGODB How to select data (countries) that only has code with 3 characters?
NOSQL MONGODB How to select data (countries) that only has code with 3 characters?

Time:11-07

SQL How to select data (countries) that only has code with 3 characters?

My issue is the same as above link, but just that i have to do it in nosql.

I have to extract all the list of countries. however in the datatable under country column (2nd column), it includes continent as well, which is not what i want.

I realised those with the first column (iso_code) with only 3 characters are data with countries, while those with more than 3 characters are continents/non country. How do i go about extracting this?

my code in extracting everything:

db.owid_energy_data.distinct("country")

CodePudding user response:

Use $strLenCP to compute the length of iso_code. $match with 3 to get the documents needed. $group to find distinct countries.

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $eq: [
          3,
          {
            "$strLenCP": "$iso_code"
          }
        ]
      }
    }
  },
  {
    $group: {
      _id: "$country"
    }
  }
])

Mongo Playground

  • Related