Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading