0

Problem is that I want to 'enter' array utwor and count average of dlugosc_utworu How looks my code:

db.artysci.aggregate({
    "$project": {
        _id: 0,
        nazwa: 1,
        nazwisko: 1,
        "numberOfSongs": {
            "$sum": {
                "$map": {
                    "input": "$album",
                    "in": { "$size": { $ifNull: ["$$this.utwor", []] } }
                }
            }
        },
        "avgSongTime":{
            "$avg": {
                    "$map": {
                        "input": "utwor",
                        "in": { $ifNull: ["$$this.dlugosc_trwania", []] }
                    }
                }
        }
    }
})

I want to make this avg of "dlugosc_trwania" who is located in utwor array in album array.

Grid:

db.artysci.insert({
    imie: 'Nik',
    nazwisko: 'Kershaw',
    rok_debiutu: 1983,
    kraj_pochodzenia: ['Wielka Brytania'],
    gatunek: 'pop',
    album: [{
            tytul:"Human Racing",
            rok_edycji:1990,
            gatunek: 'trash metal',
            typ_nosnika: 'CD',
            utwor: [{
                    numer: 1,
                    tytul_utworu: 'Dancing Girls',
                    dlugosc_trwania: 3.46
                    },
                    {
                    numer: 2,
                    tytul_utworu: 'Wouldn’t It Be Good',
                    dlugosc_trwania: 4.32
                    },
                    {
                    numer: 3,
                    tytul_utworu: 'Drum Talk',
                    dlugosc_trwania: 3.10
                    },
                    {
                    numer: 4,
                    tytul_utworu: 'Bogart',
                    dlugosc_trwania: 4.38
                    }
                   ]
            }
})

Thanks to Faizul Hassan for your help and Yours, if you help me <3

1 Answers1

0

Copy pasting the solution here from our conversation in another post..

Here is the soultion for your second question.

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] } }
      }
   },
]);
Faizul Hassan
  • 120
  • 12