Update, aggregation pipeline in pymongo not recognising field_path and taking value as literal string

I have mongodb version 5+ and latest version of pymongo from pip

I have a query it works fine in mongodb shell and compass

But when i use it in python pymongo in my code it does not work
the value is being put as “$categorization.category” as a literal string
instead it should copy the value from that field to edit field

I tried using both update_many and pipeline

Here is the document structure

{
  "some_key": "some_value",
  "categorization": {
    "edit_category": "edit_category",
    "category": "category",
  }
}
my_collection.update_many(
    filter={},
    update={
        "$set": {
            "categorization.edit_category": "$categorization.category",
        }
    },
)
my_collection.aggregate(
    pipeline=[
        {
            "$set": {
                "categorization.edit_category": "$categorization.category",
            }
        },
    ]
)

After the query expected result

{
  "some_key": "some_value",
  "categorization": {
    "edit_category": "category",
    "category": "category",
  }
}

But actual result in python

{
  "some_key": "some_value",
  "categorization": {
    "edit_category": "$categorization.category",
    "category": "category",
  }
}

But as is said the same pipeline query works in mongodb compass

please help

related to
https://www.mongodb.com/community/forums/t/how-can-we-assign-one-field-value-to-another/16396/4?u=rohit_krishnamoorthy

will not alter the collection my_collection unless you have a $merge stage.

If I understand correctly, what you want to do is:

1 Like

This should be wrapped in an array [] to indicate this is aggregation syntax and not regular update modifier $set.

Asya

1 Like

Wow this works
thanks you so much

i saw the type for in the update_many function

update: Mapping[str, Any] | _Pipeline,

i guess i missed it can also _Pipeline type

my_collection.update_many(
    filter={},
    update=[
        {
            "$set": {
                "categorization.edit_category": "$categorization.category",
            }
       },
   ],
)
2 Likes

Yes you are correct
I did this and it works

my_collection.aggregate(
    pipeline=[
        {
            "$set": {
                "categorization.edit_category": "$categorization.category",
            }
        },
       {
              "$merge": "my_collection_name"
       },
    ]
)
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.