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).
CodePudding user response:
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'}}},
])
CodePudding user response:
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))