4

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 ?

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Do you know how I could group the results by the first _id ?
I don't understand what you mean ... group by which _id?
I figured it out, wanted to group by the initial _id. Did that _id: { user_id: "$_id", type: "$skills" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.