0

I maxed out the free tier on Atlas and need to reduce the number of documents in my collection by half or more.

Is there a straight forward way to delete N number of documents. I don't need to query or search for specific documents, i just need to mass delete. I have approximately 100k documents in my collection and would like to get it down to around 10k.

I tried db.Articles.deleteMany({10000})and db.Articles.remove(10000)but i know the syntax is wrong

Below is how my documents are stored:

_id:
author:
title:
description:
url:
urlToImage:
publishedAt:
content:
summarization:
source_id:

Any help would be greatly appreciated

MaxxABillion
  • 541
  • 2
  • 9
  • 26
  • Indeed is wrong because the first parameter of the methods is the query, so you should pass a filter that matches at least 90k of your docs in the collection; ```db.Articles.deleteMany({ somethingThatStartsWith: 'A' });``` can be an example – Wiidialga18 May 31 '21 at 14:21
  • I’m not concerned about what documents are deleted…so querying for specific documents isn’t ideal I guess. – MaxxABillion May 31 '21 at 14:39

2 Answers2

3

You could use the following command to get the count:

db.collection.find({}).count()

This would give you the total number of data rows within your collection. You could then replace "N" with the desired number of elements you want to delete.

db.collection.find({}).limit(N).forEach(function(doc) {
    db.collection.remove({_id: doc._id});
})

Heads up this is computation heavy tasks and makes N+1 queries to the DB (Works like a charm for ~50K Data and fine for one-time use). For an optimal solution refer to this answer.

Karan Gaur
  • 809
  • 7
  • 20
1

If you have publishAt is date then copy this and add any date from where you want to delete then you can delete it multiple entry from DB

try {
  db. Articles.deleteMany(
       { "created" : {$gt : ISODate("2020-06-19T05:00:21.798-04:00")} }
   );
} 
catch (e) {
   print (e);
}