3

I have document in my collection

{
  _id: "8sd7f8s7df8s7df8"
  projects: [
    {
      name: inbox,
      tasks: [
        { name: 'task1' }
        { name: 'task2' }
        { name: 'task3' }
      ]
    }
  ]
}

I want to find document by _id and get number of tasks inside each project

I wrote this aggregate code but it's getting me number of tasks across all projects rather then size of each tasks array

User.aggregate([
  { $match: { _id: Mongoose.Types.ObjectId(userId)}},
  { $project: {
    _id: 0,
    'projects.name': 1,
    'projects.count': { $size: '$projects.tasks' }
  }}
])

How I should change this to get correct value?

1 Answer 1

3

Try doing an $unwind first before the $project pipeline:

User.aggregate([
    { "$match": { "_id": userId } },
    { "$unwind": "$projects" },
    { 
        "$project": {
            "_id": 0,
            "projects.name": 1,
            "projects.count": { "$size": "$projects.tasks" }
        }
    }
]).exec(callback);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @chridam, that helps.

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.