Query MongoDB by array field size

Imagine you have a MongoDB collection named repos. Each document contains an array field named languages.

For example.

{
  "url": "https://github.com/denoland/deno",
  "languages": ["TypeScript", "Rust", "Python", "JavaScript", "HTML"]
}

Find documents with exactly three languages

Use the $size operator to specify an exact array length.

db.repos.find({ languages: { $size: 3 } })

Find documents with at least three languages

Use dot notation and the $exists operator to specify a minimum array length.

db.repos.find({ 'languages.2': { $exists: true } })

Find documents with at most three languages

Use dot notation and the $exists operator to specify a maximum array length.

db.repos.find({ 'languages.3': { $exists: false } })

Find documents with between two and five languages (inclusive)

Use the $and operator to combine the “minimum” and “maximum” clauses.

db.repos.find({
  $and: [
    { 'languages.1': { $exists: true } },
    { 'languages.5': { $exists: false } },
  ],
})

Sign up for my newsletter

A monthly round-up of blog posts, projects, and internet oddments.