diff --git a/pydantic_odm/__init__.py b/pydantic_odm/__init__.py index 52376d8..0fa4edb 100644 --- a/pydantic_odm/__init__.py +++ b/pydantic_odm/__init__.py @@ -1,3 +1,3 @@ """Small async ODM for MongoDB based in Motor and Pydantic""" -__version__ = '0.1.4' +__version__ = '0.1.5' diff --git a/pydantic_odm/mixins.py b/pydantic_odm/mixins.py index 1b6771b..7115434 100644 --- a/pydantic_odm/mixins.py +++ b/pydantic_odm/mixins.py @@ -133,6 +133,20 @@ async def find_many( documents.append(document) return documents + @classmethod + async def update_many( + cls, + query: Dict[str, Dict[str, Any]], + fields: Dict[str, Union[str, Dict]], + return_cursor: bool = False, + ) -> Union[List[DBPydanticMixin], motor_asyncio.AsyncIOMotorCursor]: + """ + Find and update documents by query + """ + collection = await cls.get_collection() + await collection.update_many(query, fields) + return await cls.find_many(query, return_cursor) + @classmethod async def bulk_create( cls, documents: Union[List[BaseModel], List[Dict]], diff --git a/tests/mixin.py b/tests/mixin.py index 388bf5f..498c8f4 100644 --- a/tests/mixin.py +++ b/tests/mixin.py @@ -248,6 +248,21 @@ async def test_find_many(self, init_test_db): assert document._id assert document._doc == document.dict() + async def test_update_many(self, init_test_db): + models = [ + ExampleModel(title='Model #%d' % i, created=datetime.now(), age=i) + for i in range(1, 5) + ] + await ExampleModel.bulk_create(models) + + # Update documents whose age more than 1 and less than 4 + query = {'age': {'$gt': 1, '$lte': 3}} + fields = {'$set': {'title': 'New Model Title!'}} + updated_documents = await ExampleModel.update_many(query, fields) + for doc in updated_documents: + assert 1 < doc.age <= 3 + assert doc.title == 'New Model Title!' + async def test_update(self, init_test_db): model_data = { 'title': 'Test title',