Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB how to delete document by count fields

enter image description here

My collection has data with 10000+ records in the fields. It has two documents with 111 fields and 7 fields respectively.

I want to delete the document in collection with 7 fields. Please help suggest a query for this problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To delete a document with 7 fields, use the db.collection.deleteOne() method with the $expr query operator which allows you to use aggregate operators like $size and $objectToArray to get the number of fields in the document using the system variable $$ROOT as reference to the root document.

The following operation will delete a single document with n number of fields:

var n = 7;
db.collection.deleteOne({
    $expr: {
        $eq: [
            { $size: { $objectToArray: '$$ROOT' } },
            n // n = 7
        ]
    }    
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading