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

153
Visualizações
Mongoose - Find object with any key and specific subkey

Let's say I have a Mongo database that contains objects such as :

[
  {
    "test": {
      "123123": {
        "someField": null
      }
    }
  },
  {
    "test": {
      "323143": {
        "someField": "lalala"
      },
      "121434": {
        "someField": null
      }
    }
  },
  {
    "test": {
      "4238023": {
        "someField": "afafa"
      }
    }
  },
]

As you can see, the keys right under "test" can vary.

I want to find all documents that have at least one someField that is not null.

Something like find : "test.*.someField": { $ne: null } ( * represents any value here)

How can i do this in mongoose ? I'm thinking an aggregation pipeline will be needed here but not exactly sure how.

Constraints :

  • I don't have much control over the db schema in this scenario.
  • Ideally i don't want to have to do this logic in nodeJS, I would like to query directly via the db.
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The trickiest part here is that you cannot search keys that match a pattern. Luckily there is a workaround. Yes, you do need an aggregation pipeline.

Let's look at an individual document:

  {
    "test": {
      "4238023": {
        "someField": "afafa"
      }
    }
  }

We need to query someField, but to get to it, we need to somehow circumvent 4238023 because it varies with each document. What if we could break that test object down and look at it presented like so:

      {
        "k": "4238023",
        "v": {
          "someField": "afafa"
        }
      }

Suddenly, it get a heck of a lot easier to query it. Well, mongodb aggreation offers a function called $objectToArray which does exactly that.

So what we are going to do is:

  1. Convert the test object into an array for each document.
  2. Match only documents where AT LEAST ONE v.someField is not null.
  3. Put it back together to look as your original documents, minus the ones that do not match the null criterion.

So, here is the pipeline you need:

db.collection.aggregate([
  {
    "$project": {
      "arr": {
        "$objectToArray": "$$ROOT.test"
      }
    }
  },
  {
    "$match": {
      arr: {
        $elemMatch: {
          "v.someField": {
            $ne: null
          }
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "test": {
        $arrayToObject: "$arr"
      }
    }
  }
])

Playground: https://mongoplayground.net/p/b_VNuOLgUb2

Note that in mongoose you will run this aggregation the same way you would do it in a terminal... well plus the .then.

YourCollection.aggregate([
   ...
   ...
])
.then(result => console.log(result)) 
over 4 years ago · Santiago Trujillo 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