Amol_G
Amol_G

Reputation: 367

How to use distinct and aggregate together in single query in MongoDB?

My MongoDB document is as follow

{
    "_id" : ObjectId("622126001b68d9136e48ba4a"),
    "brand_name" : "Sony",
    "brand_rating" : [
        {
            "cust_name" : "Amit K",
            "rating" : 4
        },
        {
            "cust_name" : "Raghu",
            "rating" : 4
        }
    ],
    "models" : [
        {
            "model_name" : "Sony Xperia Z2",
            "RAM" : "3GB",
            "ROM" : "32GB",
            "price" : 18000,
            "buyer" : [
                {
                    "cust_name" : "Amit K",
                    "rating" : 5
                },
                {
                    "cust_name" : "Raghu",
                    "rating" : 4
                }
            ]
        },
        {
            "model_name" : "Sony XP",
            "RAM" : "4GB",
            "ROM" : "64GB",
            "price" : 25000,
            "buyer" : [
                {
                    "cust_name" : "Amit K",
                    "rating" : 5
                },
                {
                    "cust_name" : "Raghu",
                    "rating" : 4
                }
            ]
        }
    ]
}

I try following two queries :

> db.brand.distinct("brand_name")

Output : [ "Sony", "Samsung", "iPhone" ]

db.brand.aggregate({$addFields : {total_rating : {$sum : "$brand_rating.rating"} }}, {$sort : {total_rating : -1}}, {$limit : 1 }, {$project : {_id : 0, brand_name : 1, total_rating : 1} })

Output : { "brand_name" : "iPhone", "total_rating" : 10 }

I want to get both outputs in a single query (Desired Output)

[ "Sony", "Samsung", "iPhone" ] { "brand_name" : "iPhone", "total_rating" : 10 }

What is the easiest way to do this?

Upvotes: 0

Views: 50

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

As @rickhg12hs pointed out, you can use $facet to get something like:

{
"brand_set": [
  "Sony"
],
"top_sum": {
  "brand_name": "Sony",
  "total_rating": 8
}

}

see playground: https://mongoplayground.net/p/84NadbPpDbe

Upvotes: 1

Related Questions