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

292
Visualizações
Mongo Db $not $in query with multiple keys

I have a Mongo db collection of documents which contains _id , id1, id2, where (id1, id2) are unique together. I want to find all the documents except a list of dictionaries of (id1, id2).

In other words, I want all the documents except the except_arr.

Example of the documents:

{ _id: 1, id1: 25, id2: 1030 },
{ _id: 2, id1: 25, id2: 1031 },
{ _id: 3, id1: 1024, id2: 2048 },
{ _id: 4, id1: 1552, id2: 1284 }

Example of the array to except:

except_arr = [
    {id1: 1024, id2: 2048},
    {id1: 1552, id: 1284}
]

The result should be:

{ _id: 1, id1: 25, id2: 1030 },
{ _id: 2, id1: 25, id2: 1031 }
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

What you're looking for is called $nor

db.collection.find({
  $nor: [
    {
      id1: 1024,
      id2: 2048
    },
    {
      id1: 1552,
      id2: 1284
    }
  ]
})

Playground

over 4 years ago · Santiago Trujillo Relatório

0

After reviewing the code I've commented and see what Mohamad said I got this solution:

db.getCollection('test').find({
    $or: [ 
        { id1: { $nin: [1024, 1552] } }, 
        { id2: { $nin: [2048, 1284] } }  
    ]
})

My database objects:

[
    { _id: 1, id1: 25, id2: 1030 },
    { _id: 2, id1: 25, id2: 1031 },
    { _id: 3, id1: 1024, id2: 2048 },
    { _id: 4, id1: 1552, id2: 1284 },

    { _id: 5, id1: 1024, id2: 3 },
    { _id: 6, id1: 4, id2: 1284 }
]

The result:

[
    { _id: 1, id1: 25, id2: 1030 },
    { _id: 2, id1: 25, id2: 1031 },
    { _id: 5, id1: 1024, id2: 3 },
    { _id: 6, id1: 4, id2: 1284 }
]

EDIT
Below a example with different id1 and id2
*Online playground to test: https://mongoplayground.net/p/2vQyTkpgHNI
My collection: Collection

The query result. Query 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