Hi I am really struggling to get an insert working with MongoDB. My schema basically will look like this. I will be recording pages hits every hour. I will be recording this for many different pages so efficiency is important. I have read that updating is a lot more efficient than writing.
{
"_id" : "UniqueID:Month",
"hits": { "0" : {"0":0, "1":0, ..."23":0},
"1" : {"0":0, "1":0, ..."23":0},
...
"23" : {"0":0, "1":0, ..."23":0}
}
}
When the page does not exist I would like to insert the full schema
"hits": {"0": {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0}}...
When the page does exist simply set:
'$set': {"hits": {str(day): {str(hour): page_view}}}
I have code written:
collection.update(
{"_id": "UniqueID:" + str(month)},
{
'$set': {"hits": {str(day): {str(hour): page_view}}},
'$setOnInsert': {"hits": {"0": {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0}}}
},
True
)
My problem is that when the document does not exist it runs $set and $setOnInsert and this causes an error updating hits at the same time. Is there a way that when the document does not exist to only run $setOnInsert?
EDIT: I do not have a definitive list of pages I will be tracking so I will am unable to initially create a document for each one.
Thanks in advance.