I have a collection of documents in my MongoDB database, and each document contains an array of timezones. I want to retrieve all the documents for which the length of the "timezones" array is greater than 2

{
    _id: ObjectId("642c0ec1cb1151ed3126c87c"),
    id: 171,
    name: 'Papua new Guinea',
    iso3: 'PNG',
    iso2: 'PG',
    numeric_code: '598',
    phone_code: '675',
    capital: 'Port Moresby',
    currency: 'PGK',
    currency_name: 'Papua New Guinean kina',
    currency_symbol: 'K',
    tld: '.pg',
    native: 'Papua Niugini',
    region: 'Oceania',
    subregion: 'Melanesia',
    timezones: [
      {
        zoneName: 'Pacific/Bougainville',
        gmtOffset: 39600,
        gmtOffsetName: 'UTC+11:00',
        abbreviation: 'BST',
        tzName: 'Bougainville Standard Time[6'
      },
      {
        zoneName: 'Pacific/Port_Moresby',
        gmtOffset: 36000,
        gmtOffsetName: 'UTC+10:00',
        abbreviation: 'PGT',
        tzName: 'Papua New Guinea Time'
      }
    ],
    latitude: '-6.00000000',
    longitude: '147.00000000',
    emoji: '🇵🇬',
    emojiU: 'U+1F1F5 U+1F1EC',
    translations: {
      kr: '파푸아뉴기니',
      'pt-BR': 'Papua Nova Guiné',
      pt: 'Papua Nova Guiné',
      nl: 'Papoea-Nieuw-Guinea',
      hr: 'Papua Nova Gvineja',
      fa: 'پاپوآ گینه نو',
      de: 'Papua-Neuguinea',
      es: 'Papúa Nueva Guinea',
      fr: 'Papouasie-Nouvelle-Guinée',
      ja: 'パプアニューギニア',
      it: 'Papua Nuova Guinea',
      cn: '巴布亚新几内亚',
      tr: 'Papua Yeni Gine'
    }
  },

How can i get all the documents for which the length of timezones is greater than 2 ?

You may use $size to query based on the size of an array. Also look at https://www.mongodb.com/docs/manual/tutorial/query-arrays/.

I was using it with $gt, as i want documents for which the length of the “timezones” array is greater than 2.

but i am getting error.

Hummm! Don’t know.

You may try my hack

db.countries.find( { "timezones.2" : { "$exists" : true } } )
1 Like

wows nice post thanks