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

135
Views
MongoDB find documents but exclude those without the field

I'm trying to query a collection and sort it by a field that doesnt exist in every record. For example im calling this:

exports.getProductPriceByLosers = (req,res) => {
    Market.find()
        .sort({ "analytics.one_day_change": 1 })
        .select('analytics.one_day_change name')
        .limit(10)
        .exec((err, data) => {
            if (err){
                return res.status(400).json({
                    error: 'No products found'
                })
            }
            res.json(data)
        })
}

However the field 'one_day_change' doesn't exist on every record so the result im getting is about 20 products first without that field, and then it returns the prodcuts i do need with the correct sort. Is there a way i can tell mongo not to return those documents i dont need / dont have the data i need?

Thanks!! x

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

0

You can use $exists: true to get only documents where that field exists.

exports.getProductPriceByLosers = (req,res) => {
    Market.find({"analytics.one_day_change":{ "$exists": true}})
        .sort({ "analytics.one_day_change": 1 })
        .select('analytics.one_day_change name')
        .limit(10)
        .exec((err, data) => {
            // ...
        })
}

Check this example

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!