BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.91k stars 201 forks source link

[BUG] update_many with aggregate set fields to a nested document not the exact expression value #839

Open SolardiaX opened 5 months ago

SolardiaX commented 5 months ago

Describe the bug When use find & update_many to replace array fields frist N elements with new elements, the command update the fields value to nest document not the expresssion calculated value

To Reproduce

origin_children_ancestors = [ObjectId("65acdb2f025de11c4b6f4fa8"),ObjectId("65ad037edbe9cca114dcaf38")]
new_children_ancestors = [ObjectId("65acdb2f025de11c4b6f4fa8"),ObjectId("65ad037edbe9cca114dcaf38"), ObjectId(""65ae10c1652cea51d101c0c1"")]

await Categories.find({
    f"ancestors.{i}": val for i, val in enumerate(origin_children_ancestors)
}).update_many({
    "$set": {
        "ancestors": {
            "$concatArrays": [
                new_children_ancestors,
                {"$slice": ["$ancestors", len(origin_children_ancestors), {"$size": "$ancestors"}]}
            ]
        }
    }
})

Expected behavior "ancestors" field should be updated starts with "new_children_ancestors" array.

Additional context "ancestors" is wrong updated to a dict { "$concatArrays": [ new_children_ancestors, {"$slice": ["$ancestors", len(origin_children_ancestors), {"$size": "$ancestors"}]} ]}

SolardiaX commented 5 months ago

I think we should change the args: Mapping[str, Any] signture of the update_many method to args: Mapping[str, Any] | Sequence[Mapping[str, Any]] and used as:


await Categories.find({
    f"ancestors.{i}": val for i, val in enumerate(origin_children_ancestors)
}).update_many([{
    "$set": {
        "ancestors": {
            "$concatArrays": [
                new_children_ancestors,
                {"$slice": ["$ancestors", len(origin_children_ancestors), {"$size": "$ancestors"}]}
            ]
        }
    }
}])

Currently, this script can be executed as expect but with issue hints in IDE.

roman-right commented 5 months ago

Thank you for the catch. I'll pick this up on the next bug fixing session