How to get the count for same value data in mongodb using nodeJs

154 Views Asked by At

im having mongo data and trying get the result as below.

 [
   { "type": "chocolate", "brand":"arun","details":{ "price": 13,"state": "CA", "quantity":120 }},
   { "type": "chocolate", "brand":"arun","details":{ "price": 14,"state": "CA", "quantity": 140 }},
   { "type": "chocolate", "brand":"ibaco","details":{ "price": 13, "state": "CA", "quantity": 120 }},
   { "type": "chocolate", "brand":"ibaco","details":{ "price": 14, "state": "WA","quantity": 140 }},
   
   { "type": "vanilla", "brand":"arun","details":{ "price": 12,"state": "CA", "quantity": 145 }},
   { "type": "vanilla", "brand":"arun","details":{ "price": 13,"state": "CA", "quantity": 104 }},
   { "type": "vanilla", "brand":"ibaco","details":{ "price": 12,"state": "CA", "quantity": 145 }},
   { "type": "vanilla", "brand":"ibaco","details":{ "price": 13,"state": "WA", "quantity": 104 }}
 ]

i want a result in such a way that

if filter by type : chocolate : 4 counts, vanilla: 4 counts

if filter by type and brand :

                           chocolate && arun  : 2 counts
                           chocolate && ibaco : 2 counts
                           vanilla && arun  : 2 counts
                           vanilla && ibaco  : 2 counts

if filter by type and brand and state :

                                chocolate && arun && CA : 2 counts
                                chocolate && ibaco && CA : 1 counts
                                chocolate && ibaco && WA : 1 counts        
                                vanilla && arun && CA : 2 counts
                                vanilla && ibaco && CA : 1 counts
                                vanilla && ibaco && WA : 1 counts

                           
          Thanks in advance.
1

There are 1 best solutions below

0
YuTing On
db.collection.aggregate([
  {
    $facet: {
      type: [
        {
          $group: {
            _id: "$type",
            counts: { $sum: 1 }
          }
        }
      ],
      type_brand: [
        {
          $group: {
            _id: {
              type: "$type",
              brand: "$brand"
            },
            counts: { $sum: 1 }
          }
        }
      ],
      type_brand_state: [
        {
          $group: {
            _id: {
              type: "$type",
              brand: "$brand",
              state: "$details.state"
            },
            counts: { $sum: 1 }
          }
        }
      ]
    }
  }
])

mongoplayground


https://www.mongodb.com/docs/drivers/node/current/fundamentals/aggregation/

const pipeline = [ ... ];
const aggCursor = coll.aggregate(pipeline);
for await (const doc of aggCursor) {
    console.log(doc);
}