skip to Main Content

I have this type of data on my server.

[
    {
        "brand": "Hyundai",
        "model": "Pickup -0395",
        "price": 80000
    },
    {
        "brand": "Hyundai",
        "model": "Sports Car -0305",
        "price": 70000
    },
    {
        "brand": "Tesla",
        "model": "Sports Car -05",
        "price": 180000
    },
    {
        "brand": "Tesla",
        "model": "Sedan -95",
        "price": 150000
    },
    {
        "brand": "BMW",
        "model": "Minivan -0395",
        "price": 100000
    },
    {
        "brand": "BMW",
        "model": "Sports car -0395",
        "price": 90000
    }
]

But ,
I want to get single document/product from each brand(property).

2

Answers


  1. You can do something like this if you want to group it by brand on client side

    const grouped = (data) => data.reduce((res, {brand, ...model}) => {
      const existing = res[brand] || []
      res[brand] = [...existing, model]
      return res
    
    }, {})
    
    
    const data = [
        {
            "brand": "Hyundai",
            "model": "Pickup -0395",
            "price": 80000
        },
        {
            "brand": "Hyundai",
            "model": "Sports Car -0305",
            "price": 70000
        },
        {
            "brand": "Tesla",
            "model": "Sports Car -05",
            "price": 180000
        },
        {
            "brand": "Tesla",
            "model": "Sedan -95",
            "price": 150000
        },
        {
            "brand": "BMW",
            "model": "Minivan -0395",
            "price": 100000
        },
        {
            "brand": "BMW",
            "model": "Sports car -0395",
            "price": 90000
        }
    ]
    
    console.log(grouped(data))
    Login or Signup to reply.
  2. You’d need some criterion for which Hyundai/Tesla/BMW it is. Let’s assume you want the cheapest in any case, you could go for

    db.cars.aggregate([
      {$sort: {brand: 1, price: 1}},
      {$group: {_id: '$brand', cheapest: {$first: '$$ROOT'}}},
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search