querydrill

Learn ›Advanced aggregation ›Array and conditional expressions

$size and $arrayElemAt

arrays$arrayElemAt$project$size

Two small operators that show up constantly: $size for how many elements an array has, $arrayElemAt for pulling one out by position. $arrayElemAt is what turns a one-element $facet or $lookup result into a plain value.

Suppose:

{
  skills: [
    "Node.js",
    "MongoDB",
    "Kafka"
  ]
}
{
  $project: {
    skillCount: {
      $size: "$skills"
    }
  }
}

Result:

{
  skillCount: 3
}

Conceptually:

skills.length

$arrayElemAt

Suppose:

{
  scores: [10, 20, 30]
}

Get first:

{
  $arrayElemAt: [
    "$scores",
    0
  ]
}

Get second:

{
  $arrayElemAt: [
    "$scores",
    1
  ]
}

Conceptually:

scores[0]

Try it

db.users.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      skillCount: { $size: "$skills" },
      firstSkill: { $arrayElemAt: ["$skills", 0] }
    }
  },
  { $limit: 5 }
])

$arrayElemAt takes negative indexes too: -1 is the last element.