Question

Given this document structure:

{
    "_id": date,
    "list": [
        { hour: "something",
          hour: "something else"
        }
    ]
}
  1. How do I upsert a new doc based on the _id?
  2. How do I check to see if a key exists in my sub document and upsert to that?

What I've tried:

col.update({'_id':my_str}, {'_id':my_str, 'list':{'$addtoset':["14":"yet another thing"]}}, {'$upsert':'true'})

EDIT:

updated my structure:

{
    _id: date,
    hours: [
                { "0": "something"},
                { "1": "something else"},
                  ...
            ]
}
Was it helpful?

Solution

You cannot modify directly the internal list attribute with pymongo, need to pull the whole document and republish it:

my_doc = col.find_one({'_id': my_str})
if my_doc is not None:
    # Document exist, modify it
    my_doc['hours'].append({"14": "yet another thing"})
    col.update({'_id': my_str}, my_doc)
else:
    # Insert the new document with all the new attributes
    col.insert({'_id': my_str, 'hours': [{"14": "yet another thing"}]})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top