Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb count occurences of an element inside the array from group

I have a problem where I want to get the number of occurences of a certain element in an array as i group them. Here is my schema:

{
   "name": "John Doe",
   "age": 20,
   "address": "Nasipit, Talamban, Cebu City, Cebu",
   "visitors": [
     {
       "_id": {
         "$oid": "5de5a8271a91ca42fc5fc593"
       },
       "firstname": "Jane Doe",
       "lastname": "Tanilon",
       "address": "California",
       "date": "December 3rd 2019, 8:11:19 am"
     },
     {
       "_id": {
         "$oid": "5de5a8271a91ca42fc5fc593"
       },
       "firstname": "Nice",
       "lastname": "One",
       "address": "California",
       "date": "December 3rd 2019, 8:11:19 am"
     }
     ]
}

I tried making to group them:

db.visitors.aggregate({
    $group: {_id: '$visitors.address',count:{$sum:1}}
})

And the result is :

{ "_id" : [ "California", "California"], "count" : 1 }

And I want to count occurences of California in the array like this one:

{ "_id" : "California, "count" : 2 }

like image 417
Chervin Tanilon Avatar asked Dec 13 '25 04:12

Chervin Tanilon


1 Answers

Expression '$visitors.address' returns an array while you need to count visitors array documents separately. To do that you need to $unwind that array before running $group:

db.visitors.aggregate([
    { $unwind: "$visitors" },
    {
        $group: {_id: '$visitors.address',count:{$sum:1}}
    }
])
like image 107
mickl Avatar answered Dec 15 '25 18:12

mickl