Home > Enterprise >  MongoDB find documents but exclude those without the field
MongoDB find documents but exclude those without the field

Time:11-22

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

CodePudding user response:

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

  • Related