Update and add new key based on existing document key

Hi Team,

I stuck on finding solution when update_many with existing document key to set new document key and merge it in the same collection. (Mongo v4.0)

Scenario:

1 Used pymongo in python service to update

2 my collection is

myCollection = [
  {      
        _id: '5654xxx',
        id: 1,
        name: "Troy",
        additional: "some",
        day: "21 Apr, 2021"
  },
  {      
        _id: '5655xxx',
        id: 2,
        name: "Thor",
        day: "25 Apr, 2021"
  }
]

3 Tried firing query using pymongo as given below,

cursor = myCollection.update_many(
    {
        additional: { '$exists': True }   # to update on specific document which has **additional** key
    },
    {
        '$set': { 
                'date': '$day',   # here find **day** key from matched document and map to **date** as new key
                'newKey': 'newValue'  # adding **newKey** with **newValue** in the same document
        }
    },
    upsert=False
)

4 From above 3rd setup the cursor executed and checked in collection, it will shown as,

[
      {      
            _id: '5654xxx',
            id: 1,
            name: "Troy",
            additional: true,
            date: "$day",  #  here expecting to map with **day** value which is "25 Apr, 2021" but its mapped with $day 
            day: "25 Apr, 2021",
            newKey: "newValue"     # it is as expected 
      },
      {      
            _id: '5655xxx',
            id: 2,
            name: "Thor",
            day: "25 Apr, 2021"
      }
]

5 In above what expecting the $day value but its mapped as it is without document value scope.

Please suggest what else can do here or I missed something here.

Thanks.

Hi @Jitendra_Patwa

Thanks for raising this question, can you confirm which lesson in M220P this relates and can you provide the outputs of the pytest where you might be encountering an issue.

If this isn’t related to M220P,. I’d suggest moving this to the Working with Data category as you can find more assistance within that section to help answering your question.

Kindest regards,
Eoin