Mongoengine bulk update without objects.update ()

I would like the changes to the instances of the mongoengine docs to be expanded, but as far as I understood, model.objects.update(...)

does the same update in all the documents that meet the criteria.

Example:

entities = Foo.objects

result = entities.update(
    set__foo='new bar',
    upsert=True,
    full_result=True)

      

This sets the property foo

to new bar

for all documents that have theirs foo

equal bar

. I would like to make different changes for each document.

Is it possible? Something like that:

entities = Foo.objects

...  # make changes to each entity in entities

entities = Foo.objects.update(entities)
# these entities were bulk updated in mongodb.

      

+3


source to share


1 answer


Just back here in case anyone runs into this: mongoengine doesn't really give us any way to tell many different updates for many posts, but pymongo does! With it, I could easily write an update:

from pymongo import UpdateOne
from mongoengine import Document, ValidationError

class Foo(Document):
    ...

bulk_operations = []

for entity in entities:
    try:
        entity.validate()  
        bulk_operations.append(
            UpdateOne({'_id': entity.id}, {'$set': entity.to_mongo().to_dict()}))

    except ValidationError:
        pass

if bulk_operations:
    collection = Foo._get_collection() \
        .bulk_write(bulk_operations, ordered=False)

      



This is where I get the collection of Foo with _get_collection()

and perform a list of UpdateOne

update operations as they are generated.

+12


source







All Articles