Sunday, 2 September 2018

Delete gridfs file mongo db shell script

if we want to delete gridfs file from mongo db with chunks and file then use below script:

mydoc: is my collection that contain the reference of gridFsFileId for each document

as i want to delete all document below or equal from a particular date:


db.mydoc.find({ "creationTime": { $lte: NumberLong(1485172670719)}}).forEach(
function(mydoc){
  if(mydoc!==null){
    //remove chunk in loop
      db.fs.chunks.remove({
    "files_id": ObjectId(mydoc.gridFsFileId)
    });
    //remove file
        db.fs.files.remove({
           "_id": ObjectId(mydoc.gridFsFileId)
        });
      
      
        //remove from mydoc
      
        db.mydoc.remove({
                "gridFsFileId":  mydoc.gridFsFileId
        });
  }
}
);




No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...