Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda