arthurr
arthurr

Reputation: 1145

How to get size of array nested in another array with mongoose aggregate

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?

Upvotes: 3

Views: 2367

Answers (1)

chridam
chridam

Reputation: 103365

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);

Upvotes: 3

Related Questions