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

276
Visualizações
How to perform mongoose deleteMany() with query operators?

I want to delete X number of posts starting from the most recently created for a specific user.

How can I apply this logic using mongoose so that I can perform just ONE database operation instead of first having to query for these posts and remove them one by one?

I am finding using the query and projection operators with the $ very confusing, any help would be appreciated.

Below I added pseudo code on how it should to work.

Thank you!

const userId = "123456"
const deleteCount = 6

const deletedPosts = await Post.deleteMany({
      .where { userid == userId) }
      .sort({createdAt: -1}) // delete by most recent
      .limit(deleteCount)    // only delete 6 (most recent) posts
      }, {new: true})        // return results of operation

console.log(deletedPosts.deletedCount) // -> should be "6"

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can't set a limit when using deleteMany or findAndModify. So, if you want to precisely limit the number of documents removed, you'll need to do it in two steps.

  1. db.getCollection('users').find({}, {class : 4}) .limit(2) .sort({StudentAge: -1}) .toArray() .map(function(doc) { return doc._id; }); //returns the array of id's

  2. db.getCollection('users').deleteMany({_id: {$in: [ "s3", "s4" ]}})//put the array of id's

Data in model

1st query

2nd query

Final output

about 4 years ago · Juan Pablo Isaza 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