Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

How to count array elements in mongo

I know there are lots of topics talking about that out there but I can't figure out what goes wrong in my implementation.

I have the followings documents:

{
  "_id" : ObjectId("510a353929e16756d5000009"),
  "skills" : [
    [
      "UserEmbed::Author::Skills::Copywriting",
      "UserEmbed::Author::Skills::Proofreading",
      "UserEmbed::Author::Skills::Proofreading",
      "UserEmbed::Author::Skills::Translation",
      "UserEmbed::Author::Skills::Translation",
      "UserEmbed::Author::Skills::Translation"
    ]
  ]
}

I would like something like this:

{
  "UserEmbed::Author::Skills::Copywriting": 1,    
  "UserEmbed::Author::Skills::Proofreading": 2,
  "UserEmbed::Author::Skills::Translation": 3
}

Here is what I have (first $group is to get the document above from my original document structure):

aggregate([ { $group: { _id: "$_id", skills: { $addToSet : "$author_profile.skills._type" } } }, { $unwind : "$skills" }, { $group : { _id : "$skills", count: { $sum : 1 } } }])

Which returns something like this (with other documents):

{
  "_id" : [
    "UserEmbed::Author::Skills::Copywriting",
    "UserEmbed::Author::Skills::Copywriting",
    "UserEmbed::Author::Skills::Copywriting",
    "UserEmbed::Author::Skills::Translation",
    "UserEmbed::Author::Skills::Translation",
    "UserEmbed::Author::Skills::Translation"
  ],
  "count" : 1
}

It seems that the $group is not working properly. Did I misunderstand something ?

Upvotes: 4

Views: 3702

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59793

Given your document contains an array of arrays, you'd need to introduce a second $unwind for $skills:

db.so.aggregate([
    { $group: { _id: "$_id", 
        skills: { $addToSet : "$author_profile.skills._type" }}},
    { $unwind : "$skills" }, 
    { $unwind: "$skills" },
    { $group : { _id : "$skills", count: { $sum : 1 } } }])

Produces:

"result" : [
        {
            "_id" : "UserEmbed::Author::Skills::Translation",
            "count" : 3
        },
        {
            "_id" : "UserEmbed::Author::Skills::Proofreading",
            "count" : 2
        },
        {
            "_id" : "UserEmbed::Author::Skills::Copywriting",
            "count" : 1
        }
    ],
"ok" : 1

Upvotes: 6

Related Questions