Sorry if my title makes no sense. I'll gladly update it but I'm very new to MongoDB and I'm not sure how to ask. I've searched through many posts and documentation but I can't seem to figure this out. I'm trying to make the following change to a document. I am working in python using pymongo, but converting straight shell commands to python hasn't been an issue thus far.
{'_id': ObjectId('633c6ee4317752423543e8c8'),
'ID1': -1,
'Engagements': [
{'ID2': '-2',
'Session': [
{'GUID': '123', 'Created_Date': '01-01-2022'},
{'GUID': '012', 'Created_Date': '01-01-2021'}
]},
{'ID2': '-3',
'Session': [
{'GUID': '234', 'Created_Date': '01-02-2022'},
{'GUID': '456', 'Created_Date': '01-03-2022'}
]}
]
}
I want to find where 'GUID' == '123' and insert information there. It would look like:
{'_id': ObjectId('633c6ee4317752423543e8c8'),
'ID1': -1,
'Engagements': [
{'ID2': '-2',
'Session': [
{'GUID': '123', 'Created_Date': '01-01-2022', 'New_Info': '999'},
{'GUID': '012', 'Created_Date': '01-01-2021'}
]},
{'ID2': '-3',
'Session': [
{'GUID': '234', 'Created_Date': '01-02-2022'},
{'GUID': '456', 'Created_Date': '01-03-2022'}
]}
]
}
Converting the accepted answer to pymongo code:
collection_example.update_one({"_id": ObjectId("633c6ee4317752423543e8c8")},
{"$set": {"Engagements.$[engElem].Session.$[sessElem].newInfo": "Cool new stuff"}},
array_filters = [{"engElem.ID2": "-2"},{"sessElem.GUID": "123"}],
upsert = False)
CodePudding user response:
Here's one way to do it using "arrayFilters"
.
db.collection.update({
"_id": ObjectId("633c6ee4317752423543e8c8")
},
{
"$set": {
"Engagements.$[engElem].Session.$[sessElem].New_Info": "999"
}
},
{
"arrayFilters": [
{"engElem.ID2": "-2"},
{"sessElem.GUID": "123"}
]
})
Try it on mongoplayground.net.