How to aggregate distinct array field in mongodb?

by muriel.schmidt , in category: MySQL , a month ago

How to aggregate distinct array field in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a month ago

@muriel.schmidt 

To aggregate distinct array field in MongoDB, you can use the $unwind and $group operators. Here's an example of how you can achieve this:


Suppose you have a collection called orders, and each document in this collection has an array field called products. To aggregate distinct products in this array field, you can use the following aggregation pipeline:

1
2
3
4
5
6
7
db.orders.aggregate([
  { $unwind: "$products" },
  { $group: {
    _id: "$products",
    count: { $sum: 1 }
  }}
])


In this aggregation pipeline:

  1. The $unwind operator is used to deconstruct the products array field, which creates a separate document for each element in the array.
  2. The $group operator is then used to group the documents by the products field and calculate the count of each distinct product.


This will give you a result with distinct products in the products array field along with their respective counts.