These are chat archives for Automattic/mongoose

23rd
Apr 2016
Artur Rozwalak
@arozwalak
Apr 23 2016 14:40

hi guys, I’m looking solution to get size of array nested inside other array. this is my document in mongo

"projects" : [ 
        {
            "name" : "work",
            "title" : "Work",
            "tasks" : [ 
                {
                    "id" : "1",
                    "text" : "First",
                    "labels" : [ 
                        "home", 
                        "phone"
                    ],
                    "dueDate" : "2016-03-18T11:10:00",
                    "created" : "2016-03-10T10:10:00",
                    "completed" : false
                }, 
                {
                    "id" : "2",
                    "text" : "Second",
                    "labels" : [ 
                        "home", 
                        "phone"
                    ],
                    "dueDate" : "2016-03-18T11:10:00",
                    "created" : "2016-03-10T10:10:00",
                    "completed" : false
                }, 
                {
                    "id" : "3",
                    "text" : "Third",
                    "labels" : [ 
                        "home", 
                        "phone"
                    ],
                    "dueDate" : "2016-03-18T11:10:00",
                    "created" : "2016-03-10T10:10:00",
                    "completed" : false
                }, 
                {
                    "id" : "4",
                    "text" : "Fourth",
                    "labels" : [ 
                        "home", 
                        "phone"
                    ],
                    "dueDate" : "2016-03-18T11:10:00",
                    "created" : "2016-03-10T10:10:00",
                    "completed" : false
                }
            ]
        }
]

I’m using aggregate to get info about projects array

User.aggregate([
      { $match: { _id: Mongoose.Types.ObjectId(userId)}},
      { $project: {
        _id: 0,
        'projects.name': 1,
        'projects.title': 1,
        'projects.tasks': 1,
        'projects.count': { $size: '$projects.tasks' }
      }}
    ])
in my db I have to elements in projects array, and when I run this query I’m getting 2 in projects.count rather then 4
so I’m assuming this query counts number of elements in projects array and not in projects.tasks
how can I get size of projects.tasks?