Ahmed Elsayed
Ahmed Elsayed

Reputation: 445

is there is way to multi group in mongodb

there is way to multi group in mongodb ? document i have and want to query it

[ { _id: '1615658138236', englishName: 'samsung smart tv 50', screen_resulation: '4K', screen_size: '50' }, { _id: '1615750981674', englishName: 'lg tv 55 led uhd', screen_resulation: 'UHD', screen_size: '55' }, { _id: '1615791834538', englishName: 'samsung smart 55 inch crystal 4k', screen_resulation: '4K', screen_size: '55' } ]

for example i have 2 unknown fields i use this method to get them

    for (let i = 0; i < result[0].filters.length; i++) {
      const item = result[0].filters[i].key;
      groupBy[item] = `$${item}`;
    }

and i try to query mongodb to get count of every field

const products = await Product.aggregate([
      {
        $match: {
          category,
        },
      },
      {
        $group: {
          _id: groupBy,
          count: {
            $sum: 1,
          },
        },
      },
      {
        $sort: { count: -1 },
      },
    ]);

result i get

[
  { _id: { screen_size: '50', screen_resulation: '4K' }, count: 1 },
  { _id: { screen_size: '55', screen_resulation: 'UHD' }, count: 1 },
  { _id: { screen_size: '55', screen_resulation: '4K' }, count: 1 }
]

what i expect is :

[
  { _id: { screen_size: '50' }, count: 1 },
  { _id: { screen_size: '55' }, count: 2 },
  { _id: { screen_resulation: '4K' }, count: 2 },
  { _id: { screen_resulation: 'UHD' }, count: 1 },
]

i really find mongodb is great but very hard for me i dont know why

Upvotes: 1

Views: 41

Answers (1)

Indraraj26
Indraraj26

Reputation: 1976

You can use $facet for multiple aggregation pipelines.

db.collection.aggregate([
  {
    "$facet": {
      "screen_size_count": [
        {
          "$group": {
            "_id": "$screen_size",
            "count": {
              $sum: 1
            }
          }
        }
      ],
      "screen_resulation_count:": [
        {
          "$group": {
            "_id": "$screen_resulation",
            "count": {
              $sum: 1
            }
          }
        }
      ]
    }
  }
])

Mongo Playground: https://mongoplayground.net/p/cnEY8NV4HNs

Upvotes: 1

Related Questions