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

357
Visualizações
Query in MongoDB (Pymongo) with operator $in using with ObjectId

I have a list of ID's and I want to query a collection based on that list. The field I'm filtering is id_, it is an ObjectID.

Example:

list = ['abcd','mnop','qrst']

I want to search documents that the _id is in that list:

cursor = db.find( {"_id": { "$in": list} }   )
cursor = db.find( {"_id": { "$in": ObjectId(list)} }   )

I tried both options above and none of them worked. The first one returned empty, and the second one throws a type error: TypeError: id must be an instance of (bytes, str, ObjectId), not <class 'list'>

How can I correct my code?

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

0

As @prasad_ said, it is needed to generate the ObjectId from the string.

list_ = ['abcd','mnop','qrst']
list_ = [ObjectId(x) for x in list_]
cursor = db.find( {"_id": { "$in": list_} } )

So the "$in" operator of MongoDB refers to the list that has ObjectId's as its content.

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