'Sort query by array size (MongoDB & NodeJS)

I need to sort this query by array size. Every document on this collection has an array of other objects, what I need to do is:

  1. I need to filter this array of objects to retrieve only the ones where Date is greater than X

  2. Then I need to sort them by the array size.

     const sales = await SaleSchema.aggregate([
     {
       $match: {
         "sales.saleDate": {
           $gte: new Date(Date.now() - 1 * 60 * 1000)
         }
       }
     },
     {
       $project: {
         "contract": 1,
         "description": 1,
         "image": 1,
         "title": 1,
         "totalSupply": 1,
         sales: {
           $filter: {
             input: "$sales",
             as: 'sale',
             cond: {
               $gte: ['$$sale.saleDate', new Date(Date.now() - 1 * 60 * 1000)]
             }
           } 
         }
       }
     },
     {
       $addFields: {
         "arraySize": {
           "$size": "$sales"
         }
       }
     },
     {
       $sort: {
         "arraySize": 1
       }
     },
     {
       $limit: 10
     }
    ]);
    

It is not working, I had a very similar query that was working, but when I created this filter for the sales array, that stopped working and I need to remake the query, but this one is not working tho..



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source