I'm new to MongoDB
and already inserted a table to my collection. Now I have new data (added new rows and updated values) but I don't know update_one
or update_many
which one should be used to update the records in the collection.
The data in my database
from pymongo import MongoClient, UpdateOne
import pandas as pd
{
"_id" : ObjectId("6143b5b78d248ba8ed0c3d88"),
"Sector" : "A",
"RKK_T" : 0.15,
"RKK_M" : 0.2,
"lastModified" : ISODate("2021-09-16T22:23:45.411Z")
},
{
"_id" : ObjectId("6143b5b78d248ba8ed0c3d89"),
"Sector" : "B",
"RKK_T" : 0.22,
"RKK_M" : 0.3,
"lastModified" : ISODate("2021-09-16T22:23:45.411Z")
}
And this is my new data that I want to push it to the database
data = [{
"_id" : "6143b5b78d248ba8ed0c3d88",
"Sector" : "A",
"RKK_T" : 0.15,
"RKK_M" : 0.25,
"lastModified" :datetime.utcnow()
},
{
"_id" : "6143b5b78d248ba8ed0c3d89",
"Sector" : "B",
"RKK_T" : 0.22,
"RKK_M" : 0.3,
"lastModified" : datetime.utcnow()
},
{
"_id" : "6143b5b78d248ba8ed0c3d90",
"Sector" : "C",
"RKK_T" : 0.25,
"RKK_M" : 0.32,
'RKK_K' : 0.4,
"lastModified" : datetime.utcnow()
}
]
df = pd.DataFrame(data, columns=['_id', 'Sector', 'RKK_T', 'RKK_M', 'lastmodified'])
df
_id Sector RKK_T RKK_M lastmodified
0 6143b5b78d248ba8ed0c3d88 A 0.15 0.25 NaN
1 6143b5b78d248ba8ed0c3d89 B 0.22 0.30 NaN
2 6143b5b78d248ba8ed0c3d90 C 0.25 0.32 NaN
So I think I need to filter by each Sector
and update values of RKK_T
and RKK_M
columns.
So based on my research I think one way to update the collection
with new data
is
for i in range(len(data)):
print(i)
for key, values in data[i].items():
# print(key, values)
collection.update_one({'Sector': 'Sector'},
{'$set': {key.keys()[i]: values.values()[i]}, "$currentDate": {"lastModified": True}},
upsert=True)
but got this error
AttributeError: 'str' object has no attribute 'keys'
I really need a help for kick start:) Thanks in advance!
pymongo update_one(), upsert=True without using $ operators
PyMongo & Pandas - Update multiple records in MongoDB collection from dataframe by matching id