Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda