Update MongoDB Documents

Updating entries typically begins by retrieving existing records using methods such as get(), filter(), or first(), followed by modifying the required fields and committing the changes using the save() method. When only certain attributes need to be updated, save(update_fields=[...]) ensures that only specified fields are written back to the database. For direct database-level updates without loading model instances into memory, QuerySet.update(**kwargs) executes the pymongo query update statement efficiently.

When the existence of a record is uncertain, update_or_create() attempts to locate an entry based on lookup parameters and applies updates using the defaults dictionary, or creates a new record if none is found.

More information on updating methods can be found in the Django queryset reference

Update documents in a Collection

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.ObjectIdField()
    headline = models.CharField(max_length=255)
copy code

Create an init.json fixture that looks like this:

init.json

[
  {
    "model": "myapp.entry",
    "pk": "61d2d6c07d26e98969f8b8c2",
    "fields": {
      "headline": "The Headline",
      "blog": { "name": "John", "content": "content" },        
    }
  },
  {
    "model": "myapp.entry",
    "pk": "61d2d6c07d26e98969f8b8c3",
    "fields": {
      "headline": "Breaking News",
      "blog": { "name": "James", "content": "content" },        
    }
  }
]
copy code

Load the fixture data into MongoDB:

python manage.py loaddata init.json
copy code

Update a single document

In myapp/management/commands/main.py write:

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(headline='The Headline')
        entry.headline = 'Breaking News'
        entry.save()
copy code

The following pymongo commands are generated:

db["myapp_entry"].find(filter={'headline': {'$eq': 'The Headline'}},
                       limit=21,
                       projection=['_id', 'headline'])
db["myapp_entry"].update_many(filter={'_id': {'$eq': ObjectId('61d2d6c07d26e98969f8b8c2')}},
                              update={'$set': {'headline': 'Breaking News'}})
copy code