Remove documents from MongoDB

Define the models in models.py to setup the relevant collections in the database.

models.py

from djongo import models

class Entry(models.Model):
    _id = models.IntegerField(primary_key=True)
    headline = models.CharField(max_length=255)
copy code

Create an init.json fixture that looks like this:

init.json

[
  {
    "model": "myapp.entry",
    "pk": "1",
    "fields": {
      "headline": "The Headline",
    }
  },
  {
    "model": "myapp.entry",
    "pk": "2",
    "fields": {
      "headline": "Breaking News",
    }
  }
]
copy code

Load the fixture data into MongoDB:

python manage.py loaddata init.json
copy code

Delete all documents

To remove all documents in the collection, run the following.

main.py

from django.core.management.base import BaseCommand
from models import Entry

class Command(BaseCommand):
    help = "Main execution file"

    def handle(self, *args, **options):
        Entry.objects.filter().delete()
copy code

Next, in the command line run:

python manage.py main
copy code

The following pymongo commands are generated:

db["myapp_entry"].delete_many({'filter': {}})
copy code

Delete all documents that match a condition

To remove a specific set of documents in the collection, run the following.

main.py

from django.core.management.base import BaseCommand
from models import Entry

class Command(BaseCommand):
    help = "Main execution file"

    def handle(self, *args, **options):
        docs_models.Entry.objects.filter(_id__lt=2).delete()
copy code

Next, in the command line run:

python manage.py main
copy code

The following pymongo commands are generated:

db["myapp_entry"].delete_many({'filter': {'_id': {'$lt': 2}}})
copy code

Delete only one document that matches a condition

You can remove a single document in the collection using, for example, with the primary key.

main.py

from django.core.management.base import BaseCommand
from models import Entry

class Command(BaseCommand):
    help = "Main execution file"

    def handle(self, *args, **options):
        entry = Entry.objects.get(_id=1)
        entry.delete()
copy code

Next, in the command line run:

python manage.py main
copy code

The following pymongo commands are generated:

db["myapp_entry"].delete_many({'filter': {'_id': {'$in': [1]}}})
copy code