2

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.

phunks
  • 29
  • 2
  • this is unfortunately a bug with mongo. you'll have to work around it as i did http://stackoverflow.com/questions/27552352/mongodb-duplicate-fields-in-set-and-setoninsert – jtmarmon Mar 11 '15 at 18:16
  • Thanks managed to get a workaround its just not as nice as I would have hoped. Hopefully in future releases they manage to fix it. – phunks Mar 12 '15 at 13:32
  • phunks - what was the workaround? – Matt Dell Apr 21 '17 at 20:46

0 Answers0