Update

Update a document

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

models.py

from djongo import models

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

Then, 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.objects.create(headline='h1')
        entry = Entry.objects.get(headline='h1')
        entry.headline = 'h2'
        entry.save()
copy code

The following pymongo commands are generated:

db['myapp_entry'].insert_many(
    [{'headline': 'h1'}],
    ordered=False)
db["myapp_entry"].find(filter={'headline': {'$eq': 'h1'}},
                       limit=21,
                       projection=['_id', 'headline'])
db["myapp_entry"].update_many(filter={'_id': {'$eq': ObjectId('6996c6255bd15eba6106f503')}},
                              update={'$set': {'headline': 'h2'}})
copy code

Bulk Write

MongoDB lets you perform Bulk Write operations using bulk_write. Perform Bulk writes as follows:

class BulkWrite:
    def __init__(self,
                 ordered=True):
copy code

Arguments

ArgumentTypeDescription
orderedbooleanPerform the write operations either in order or arbitrarily.

Example

from djongo import BulkWrite

with BulkWrite():
    entry = Entry.objects.get(pk=p_key) # Queries the DB once
    entry.headline = 'The Beatles reconcile'
    entry.save() # Djongo does not really do a update to MongoDB
    Entry.objects.create(name='How the beatles reconciled') # Djongo does not really do a insert to MongoDB

# On exit, does: db.entry.bulk_write([UpdateOne(), InsertOne()])
copy code

Unordered Bulk Writes

Example

from djongo import BulkWrite

with BulkWrite(ordered=False):
    entry = Entry.objects.get(pk=p_key) # Queries the DB once
    entry.headline = 'The Beatles reconcile'
    entry.save() # Djongo does not really do a update to MongoDB
    Entry.objects.create(name='How the beatles reconciled') # Djongo does not really do a insert to MongoDB

# On exit, does: 
# db.entry.bulk_write(
#   [UpdateOne(), InsertOne()]
#   ordered=False)
copy code