Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
How can I query for specific number of documents but couldn't be duplicate of a specific property's value

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).

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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'}}},
])
about 4 years ago · Juan Pablo Isaza Report

0

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))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!