'How to update key values by append the existing one for the record in MongoDb collection

I have a Collection allRecords as

{'name':'tom', 'subjects':'Physics'}
{'name':'jerry', 'subjects':'Maths'}

I have one json file is testData.json as

{names:",tom,jerry", subject:" chemistry, bio", title:"science"}
{names:",pot,tom", subject:" Social science", title:"humanities"}

I want to update AllRecords collection as

{'name':'tom', 'subjects':'Physics chemistry, bio science '}
{'name':'jerry', 'subjects':'Maths chemistry, bio science'}

I am trying the following code

df=pd.read_json('testData.json', lines=True)

df['names'] = [i[1:-1] for i in df['names']]
df['names'] = df['names'].str.split(',')
df = df.explode('names').reset_index(drop=True)
print(df['names'])

print(df)
for i, row in tqdm(df.iterrows()):    
            
        allRecord.update(
        {"name": row['names']},
        {"$addToSet": {"$subjects": f"{row['subject']{row['title']}" } })
        allRecords.update(
        {"name": { "$nin" :["names"]}},
        {"$set":{"subjects":f"{row['subject']} {row['title']}"}})

However, it gives me an error "The dollar ($) prefixed field '$subjects' in '$subjects' is not valid for storage."



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source