How to use Mongo aggregate to create distinct items from array

Viewed 40

I am having trouble understanding how to use aggregate pipelines in Mongo.

Given the list following documents:

db.dishes.insertMany([
    {_id: "Vanilla Sundae", keywords: ["vanilla", "ice cream", "desert"] },
    {_id: "Vanilla Cake", keywords: ["vanilla", "cake", "baking", "desert"] },
    {_id: "Chocolate Cake", keywords: ["chocolate", "cake", "baking", "desert"] }
])

How do I create an aggregate that would return a list of distinct keywords and counts of docs by keywords:

[
    {"_id": "vanilla", "count": 2},
    {"_id": "ice cream", "count": 1},
    {"_id": "desert", "count": 3},
    {"_id": "baking", "count": 2},
    {"_id": "cake", "count": 2},
    {"_id": "chocolate", "count": 1}
]
2 Answers

You can use $unwind and $group to deconstruct and reconstruct the array

db.collection.aggregate([
  {  $unwind: "$keywords" },
  {
    $group: {
      _id: "$keywords",
      count: { $sum: 1 }
    }
  }
])

Working Mongo playground

You can use unwind combined with group operator to achieve this.

db.collection.aggregate([ { "$unwind": { path: "$keywords" } }, { "$group": { "_id": "$keywords", "count": { $sum: 1 } } }, ])

This should do the trick! :)

I'm attaching the MongoDB playground here.

Related