Delete document that has size greater than a specific value

Viewed 788

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?

2 Answers

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 } } )

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 } });
Related