Search code examples
mongodbnosqlnosql-aggregation

MongoDb count elements of array in array by $size


I need help to count the elements of an array when it is in another array.

My command, when I tried to select the second array is,

db.artysci.aggregate([
   {
      $project: {
          _id:0,
         nazwa: 1,
         nazwisko: 1,
         numberOfSongs: { "album": {$size: "$utwor"}}
              
      }
   }
] )

Grid:

db.artysci.insert({
    imie: 'Laurie',
    nazwisko: 'Adkins',
    rok_debiutu: 2006,
    kraj_pochodzenia: ['Wielka Brytania'],
    gatunek: 'neo soul',
    album: [{
            tytul:"19",
            rok_edycji:2007,
            gatunek: 'pop',
            typ_nosnika: 'CD',
            utwor: [{
                    numer: 1,
                    tytul_utworu: 'Daydreamer',
                    dlugosc_trwania: 3.41
                    },
                    {
                    numer: 2,
                    tytul_utworu: 'Best for Last',
                    dlugosc_trwania: 4.19
                    },
                    {
                    numer: 3,
                    tytul_utworu: 'Chasing Pavements',
                    dlugosc_trwania: 3.31
                    }
                    ]
            }]
          })

Output when counting by $size:"$album",

{ 
    "nazwisko" : "Adkins", 
    "numberOfSongs" : {
        "album" : NumberInt(3)
    }
}

How can I count elements of an array in an array by $size?


Solution

  • @Kacper,

    Here is the soultion for your second question.

    Yes, you can achieve it in either way, using the above method or using unwind and do the average..

    Lets see an example using unwind:

    Without divide/second:

     db.notifications.aggregate([
           { $unwind: "$album" },
           { $unwind: "$album.utwor" },
           {
              $group: {
                 _id: "$_id",
                 avgDuration: { $avg: "$album.utwor.dlugosc_trwania" }
              }
           },
        ]);
    

    With divide/second:

    db.notifications.aggregate([
       { $unwind: "$album" },
       { $unwind: "$album.utwor" },
       {
          $group: {
             _id: "$_id",
             avgDuration: { $avg: { $divide: ["$album.utwor.dlugosc_trwania", 60] } }
          }
       },
    ]);