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

127
Visualizações
Check if two property of a nested document are equal in mongodb

I have a user.expenses collection like this

{
    userId: ObjectId("62f332b93753ac926ff6ac62"),
    expenses: [ 
        { 
            name: 'electricity',
            assigned: 400,
            given: 400,
        },
        {
            name: 'restaurant',
            assigned: 2100,
            given: 0,
        }
    ]
}

I will get userId and expenses.name(electricity) from the request. I need to check if the user.expenses collection has any expenses document whose name is electricity and assigned is not equal to given.

I used $elemMatch and could check if there are any embedded documents whose name is electricity.

db.user.expenses.find({
    userId: ObjectId('62f332b93753ac926ff6ac62'),
    expenses: {
        $elemMatch: {
            name: 'electricity',
        },
    },
});

EDIT

I also tried to use $where. But it only can be applied to the top-level document.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Query

  • you cant do it with query operators because you want to reference a field but you can do it with aggregate operators and $filter
  • filter the array and keep only if electricity and assigned!=given
  • keep the document if at least one sub-document was electricity with assigned!=given

Playmongo

aggregate(
[{"$match": 
   {"$expr": 
     {"$ne": 
       [{"$filter": 
           {"input": "$expenses",
            "cond": 
             {"$and": 
               [{"$eq": ["$$this.name", "electricity"]},
                 {"$ne": ["$$this.assigned", "$$this.given"]}]}}}, []]}}}])
about 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