function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michael MMichael M 

How to delete contentdocuments

Hello, I need to delete certain documents. This is the code I've been using:
    List<ContentDocumentLink > docs;
        docs = [SELECT Id, Linkedentity.name, Linkedentity.id,ContentDocument.CreatedDate  
                FROM contentDocumentLink 
                WHERE Linkedentityid 
                IN (SELECT Id FROM lead where createddate < Last_N_Days:7  ];  
            delete docs;

After I execute this, it looks like the contentDocumentLinks become deleted, however my storage usage is still the same number and percentage.Will the above code completely delete those files? 
Best Answer chosen by Michael M
Danish HodaDanish Hoda
Hi Michael,
Deleting ContentDocumentLink deletes the attachment on a parent object but not delete entirely from the org.
When a ContentDocument is created, two ContentDocumentLink  recorsd are created, one with the parent object and the other with the user creating it.

All Answers

Danish HodaDanish Hoda
Hi Michael,
Deleting ContentDocumentLink deletes the attachment on a parent object but not delete entirely from the org.
When a ContentDocument is created, two ContentDocumentLink  recorsd are created, one with the parent object and the other with the user creating it.
This was selected as the best answer
ANUTEJANUTEJ (Salesforce Developers) 
HI Michael,

I found the below link which discusses on how to manage the storage and have you tried executing the soql query in the query editor to check if the records are being returned or not?

>> https://help.salesforce.com/articleView?id=admin_monitorresources.htm&type=5

I hope this helps and in case if this information helped in your issue can you please mark this as the best answer so that it can e used by others in the future.

Regards,
Anutej
Michael MMichael M
Danish,

So how would I need to write the query for the list, that would actually the delete those contentdocuments? 
Michael MMichael M
Also, how would i query ContentDocuments that are only attached to Lead records? 
Michael MMichael M
I'm not understanding this. 

When I run this query: select Id FROM ContentDocumentlink WHERE linkedentityid in (select id from lead ) and contentdocument.createddate < LAST_N_DAYS:1, it returns 63,000 results. 

However, when I run this query: select Id FROM ContentDocument WHERE createddate < LAST_N_DAYS:1 , it only returns 52 results. How can there be so many more contentdocumentlinks than content documents? 
Danish HodaDanish Hoda
Please check if there is any trigger on ContentDocument object which might be running a loop and creating so many ContentDocumentlink  records