How to count array elements in mongo

I know that there are many topics talking about this, but I can’t understand what went wrong in my implementation.

I have the following 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's what I have (the first $group should 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 } 

$group seems to be working incorrectly. I didn’t understand something?

+4
source share
1 answer

Given that your document contains an array of arrays, you need to enter the 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 } } }]) 

It 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 
+6
source

Source: https://habr.com/ru/post/1490462/


All Articles