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

118
Visualizações
mongodb filter documents from an array of ids

I have a collection in MongoDB which looks something like this

{
  "_id": ObjectId("62a2ef1084020f45678c8740"),
  "content_id": 436629,
  "isLocked": true,
  "type": "video",
  "created_at": ISODate("2022-06-10T12:43:20.563+05:30"),
  "updated_at": ISODate("2022-06-10T12:43:20.563+05:30"),
  "__v": 0
}

Assume there are thousands of this. Now i have an array of content_id coming from a diff api

[{
  "content_id": 123456
}, {
  "content_id": 456789
}, {
  "content_id": 453211
}....]

I want to check if the array has an id for which a doc exists in the collection and fulfils the condition "isLocked": false and increment a counter based on it. One solution would be to loop the array by for or map and run a find query to check each document one by one, like

for (let i = 0; i < array.length; i++) {
  let result = await db.collection.find({
    "content_id": array[i].content_id
  });
  if (result && result.length > 0 && result[0].isLocked === false) {
    counter++;
  }
}

This would not be an ideal solution as it would be very slow. Does Mongodb has something which can achieve the same results while being more performant or i am left with this solution?

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

0

How about using $in?

array = array.map(item => item.content_id) // becomes ["id1", "id2","id3"...]

Then use following query

let result = await db.collection.find({ "content_id": { $in: array }, isLocked : false })

if you just want total number of resulted documents you can just result.length or replace .find with .countDocuments

For more performance, remember to index content_id + isLocked

e.g.

db.collection.createIndex(
  { content_id: 1, isLocked: 1 } ,
  { name: "Content Id and isLocked" }
)
about 4 years ago · Santiago Gelvez 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