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)
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" },
}
}
]
Load the fixture data into MongoDB:
python manage.py loaddata init.json
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()
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'}})
Update Multiple Documents
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.filter(headline='The Headline').update(headline='Breaking News')
The following pymongo commands are generated:
db["myapp_entry"].update_many({'filter': {'headline': {'$eq': 'The Headline'}},
'update': {'$set': {'headline': 'Breaking News'}}})
Bulk Write
MongoDB lets you perform Bulk Write operations
using bulk_write. Perform Bulk writes as follows:
main.py
from django.core.management.base import BaseCommand
from models import Entry
from djongo import BulkWrite
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
with BulkWrite():
entry = Entry.objects.get(pk=p_key)
entry.headline = 'The Beatles reconcile'
entry.save()
Entry.objects.create(name='How the beatles reconciled')
Next, in the command line run:
python manage.py main
The following pymongo command is generated:
db['myapp_entry'].bulk_write([UpdateOne(), InsertOne()])
