{ "_id" : 1, "title" : "The Pillars of Society", "tags" : [ "painting", "satire", "Expressionism", "caricature" ] }
{ "_id" : 2, "title" : "Melancholy III", "tags" : [ "woodcut", "Expressionism" ] }
{ "_id" : 3, "title" : "Dancer", "tags" : [ "oil", "Surrealism", "painting" ] }
{ "_id" : 4, "title" : "The Great Wave off Kanagawa", "tags" : [ "woodblock", "ukiyo-e" ] }
{ "_id" : 5, "title" : "The Persistence of Memory", "tags" : [ "Surrealism", "painting", "oil" ] }
{ "_id" : 6, "title" : "Composition VII", "tags" : [ "oil", "painting", "abstract" ] }
{ "_id" : 7, "title" : "The Scream", "tags" : [ "Expressionism", "painting", "oil" ] }
{ "_id" : 8, "title" : "Blue Flower", "tags" : [ "abstract", "painting" ] }
Assume we execute next:
db.exhibits.aggregate( [ { $unwind: "$tags" }, { $sortByCount: "$tags" } ] )
1) result of $unwind:
{ "_id" : 1, "title" : "The Pillars of Society", "tags" :"caricature" }
{ "_id" : 1, "title" : "The Pillars of Society", "tags" : "Expressionism" }
{ "_id" : 1, "title" : "The Pillars of Society", "tags" : "satire" }
{ "_id" : 1, "title" : "The Pillars of Society", "tags" : "painting" }
{ "_id" : 2, "title" : "Melancholy III", "tags" : "Expressionism" }
{ "_id" : 2, "title" : "Melancholy III", "tags" : "woodcut" }
{ "_id" : 3, "title" : "Dancer", "tags" : "painting" }
...
2) next stage with $sortByCount:
{ "_id" : 1, "title" : "The Pillars of Society", "tags" :"caricature" }
{ "_id" : 1, "title" : "The Pillars of Society", "tags" : "Expressionism" }
{ "_id" : 1, "title" : "The Pillars of Society", "tags" : "satire" }
{ "_id" : 1, "title" : "The Pillars of Society", "tags" : "painting" }
{ "_id" : 2, "title" : "Melancholy III", "tags" : "Expressionism" }
{ "_id" : 2, "title" : "Melancholy III", "tags" : "woodcut" }
{ "_id" : 3, "title" : "Dancer", "tags" : "painting" }
...
{ "_id" : "painting", "count" : 6 }
{ "_id" : "oil", "count" : 4 }
{ "_id" : "Expressionism", "count" : 3 }
{ "_id" : "Surrealism", "count" : 2 }
{ "_id" : "abstract", "count" : 2 }
{ "_id" : "woodblock", "count" : 1 }
{ "_id" : "woodcut", "count" : 1 }
{ "_id" : "ukiyo-e", "count" : 1 }
{ "_id" : "satire", "count" : 1 }
{ "_id" : "caricature", "count" : 1 }