Skip to content

Support update with aggregation pipeline in modify method #2874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,4 @@ that much better:
* Terence Honles (https://github.com/terencehonles)
* Sean Bermejo (https://github.com/seanbermejo)
* Juan Gutierrez (https://github.com/juannyg)
* Gowtham V Bhat (https://github.com/gowthamvbhat)
10 changes: 9 additions & 1 deletion mongoengine/queryset/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,7 +733,15 @@ def modify(
query["$where"] = where_clause

if not remove:
update = transform.update(queryset._document, **update)
if "__raw__" in update and isinstance(
update["__raw__"], list
): # Case of Update with Aggregation Pipeline
update = [
transform.update(queryset._document, **{"__raw__": u})
for u in update["__raw__"]
]
else:
update = transform.update(queryset._document, **update)
sort = queryset._ordering

try:
Expand Down
29 changes: 29 additions & 0 deletions tests/queryset/test_modify.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,35 @@ class BlogPost(Document):
)
assert blog.tags == ["python", "go", "rust", "code", "java"]

def test_modify_with_aggregation_update(self):
"""Ensure that the 'aggregation_update' modify works correctly."""

class BlogPost(Document):
slug = StringField()
tags = ListField(StringField())

BlogPost.drop_collection()

post = BlogPost(slug="test")
post.save()

BlogPost.objects(slug="test").update(
__raw__=[{"$set": {"slug": {"$concat": ["$slug", " ", "$slug"]}}}],
)
post.reload()
assert post.slug == "test test"

post = BlogPost.objects(slug="test test").modify(
__raw__=[
{"$set": {"slug": {"$concat": ["$slug", " ", "it"]}}}, # test test it
{
"$set": {"slug": {"$concat": ["When", " ", "$slug"]}}
}, # When test test it
],
new=True,
)
assert post.slug == "When test test it"


if __name__ == "__main__":
unittest.main()
Loading