简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM