1

I have a program where tasks get done in "batches". The top-level view of my documents look like this:

{
  _id: "xxx",
  status: "done",
  startedAt: 123456,
  finishedAt: 789101112,
  tasks: [...] // Huge array of deeply nested objects
}

Is it possible to construct a query for mongodb that returns only the length of the tasks array in this example?

Desired result:

{
  _id: "xxx",
  status: "done",
  startedAt: 123456,
  finishedAt: 789101112,
  numTasks: 9999
}

Thank you in advance for any advice you can give.

1

1 Answer 1

1

You can use $size

db.collection.aggregate([
  {
    $addFields: {
      numTasks: {
        "$size": "$tasks"
      }
    }
  }
])

Working Mongo playground

Sign up to request clarification or add additional context in comments.

1 Comment

Spot on! Thank you for your advice. And thanks for the mongo playground link, this is gonna be a huge help in the future!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.