How to aggregate distinct array field in mongodb?

by muriel.schmidt , in category: MySQL , 3 months ago

How to aggregate distinct array field in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 3 months 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.

Related Threads:

How to aggregate data from references in mongodb?
How to aggregate data in MongoDB using PHP?
How to implement aggregate method (pipeline) on mongodb?
How to get distinct value from array in javascript?
How to update field by multiply field value in mongodb?
How to find a substring in a field in mongodb?