Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!