0

Hello i am creating a new Web Application for products selling using MEAN stack and i added some brands(HP,ASUS..) now i created an aggregation to show every brand and how many pc have 8 Gb , how many PC have 4 GB etc. this is my data:

    [
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f68"),
    "brand": "6178524a5ff14e633aeff1ea",
    "SerialNumber": "45454234324",
    "ram": "4gb"
  },
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f69"),
    "brand": "6178524a5ff14e633aeff1ea",
    "SerialNumber": "azazz5245454az",
    "ram": "8gb"
  },
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f70"),
    "brand": "sony",
    "SerialNumber": "azazz5245454az",
    "ram": "8gb"
  },
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f71"),
    "brand": "sony",
    "SerialNumber": "azazz5245454az",
    "ram": "16gb"
  },
  {
    "_id": ObjectId("617b0dbacda6cbd1a0403f72"),
    "brand": "sony",
    "SerialNumber": "azazz5245454az",
    "ram": "16gb"
  }
]

and this is m code :

    db.b.aggregate([
{$group:{ _id:{ r:"$ram" ,b:"$brand"}, cnt:{$sum:1} }}  ,
{$project:{ a:[{k:"$_id.r" ,v:"$cnt"}] , brand:"$_id.b" ,_id:0}   },
{$project:{d:{$arrayToObject:"$a"} ,brand:1 }  } ,
{$group:{ _id:"$brand", ram:{$push:"$d"}  }} ,
{$project:{_id:0,brand:"$_id" ,"options": { $mergeObjects: "$ram" } }},
{$replaceRoot: {  newRoot: { $mergeObjects: ["$$ROOT", "$options"] }}}, 
{$project:{options:0}}   ])

this what im getting as a result :

{ "brand" : "sony", "16gb" : 2, "8gb" : 1 }

while im trying to get :

{ "brand" : "sony", "16gb" : 2, "8gb" : 1  , "sum" : 3}
4
  • 1
    You just want the total right? something like this mongoplayground.net/p/LxHHLGm278W Commented Dec 2, 2021 at 13:57
  • 1
    i think its the same as the previous one with sum added, check it to be sure, i updated it, and added the sum also. Commented Dec 2, 2021 at 14:04
  • 1
    yes it works just fine thank you so much Commented Dec 2, 2021 at 14:11
  • yes it the same i used the same method thanks Commented Dec 2, 2021 at 14:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.