Well i'm trying to swap for MonogDB but i facing a dumb question here with PYMONGO, and i arealdy tried several things here and already spend a half of my day trying to figure out how to solve this question.
As i said above it's a basic doubt about CRUD operation, where I'm trying to update a document over MongoDB.
The structure from the document inside the database is that:
{
_id: 123456,
key_stock: '756159'
stock: 'abc',
code: 'cba',
qrtly_result: {
'30/01/2000': {
'item1': '123',
'item2': '321',
'item3': '987',
}
}
}
Then i trying to update this document this way:
# Connect @ DB:
client = MongoClient(connect_db.uri)
db = client.get_database(connect_db.data_base)
collection = db[connect_db.collection]
# New DICT
result = {
'30/09/2020':{
'item1': '123',
'item2': '321',
'item3': '987',
},
'30/06/2020':{
'item1': '123',
'item2': '321',
'item3': '987',
},
}
# Update @ DB:
collection.update_one(
{'key_stock': 756159},
{'$set': {'qrtly_result': result}}
)
# If i use this way all doc going to root of the document
# but i need this new dict go for "qrtly_results"
collection.update_one(
{'key_stock': 756159},
{'$set': 'result'}
)
Any suggestion how to solve this?
Regard's, Felipe Cid
First thing it's that key_stock
is a string in your database, but it's an int in your update query. the type is important to match variables
If you want to replace the qrtly_result
, fixing the data type will work with work. try it here
But, If you want to add values to qrtly_result
, your query should look like something like this:
db.collection.update({
"key_stock": 756159
},
{
"$set": {
"qrtly_result.30/09/2020": {
"item1": "123",
"item2": "321",
"item3": "987",
},
"qrtly_result.30/06/2020": {
"item1": "123",
"item2": "321",
"item3": "987",
}
}
})
Try it here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.