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

310
Visualizações
Delete document that has size greater than a specific value

I have a collection which contains a multiple documents whose size has increased from 16MBs or is about to reach 16MBs. I want query that finds documents which have size greater than 10MBs and delete all of them.

I am using following to find the size of document.

Object.bsonsize(db.test.findOne({type:"auto"}))

Is there a way to embed this query inside db.test.deleteMany() query?

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

0

This following query deletes the documents with size greater than the specified size (the size is specified in bytes). This query is valid with MongoDB v4.4 or higher.

db.collection.deleteMany( { 
    $expr: { $gt: [ { $bsonSize: "$$ROOT" }, SIZE_LIMIT ] }, 
    type: "auto" 
} )

The following script runs for MongoDB v4.2 or earlier:
const SIZE_LIMIT = 75 // substitute your value here in bytes
let idsToDelete = [ ]
let crsr = db.collection.find()

while(crsr.hasNext()) {
    let doc= crsr.next()
    if (Object.bsonsize(doc) > SIZE_LIMIT) {
        idsToDelete.push(doc._id)
    }
}

db.collection.deleteMany( { _id: { $in: idsToDelete } } )
over 4 years ago · Santiago Trujillo Relatório

0

I think you have to do it like this:

db.test.aggregate([
   { $match: { type: "auto" } },
   { $project: { bsonSize: { $bsonSize: "$$ROOT" } } },
   { $match: { bsonSize: { $gt: 16e6 } } },
]).forEach(function (doc) {
   db.test.deleteOne({ _id: doc._id });
})

Or if you prefer deleteMany:

var ids = db.test.aggregate([
   { $match: { type: "auto" } },
   { $project: { bsonSize: { $bsonSize: "$$ROOT" } } },
   { $match: { bsonSize: { $lt: 16e6 } } }
]).toArray().map(x => x._id);

db.test.deleteMany({ _id: { $in: ids } });
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