Pymongo update_one (), upsert = True without using the $ operators

I have documents in the form:

{"hostname": "myhost1.com", "services": { ... } }

I would like to do the following:

dataset = requests.get('http://endpoint.com/hardware.json').json()
for hostname, services in dataset[0].items():
    db.titleHardware.update_one({'hostname':hostname},
                                {services.keys()[0]: services.values()[0]}, 
                                True) #upsert

However, I get the following error:

ValueError: update only works with $ operators

Is there a way to perform this update of the entire "services"key-based fragment "hostname"(and ultimately insert a new document if it hostnamedoes not exist)? I know that I can write logic to compare what is in my MongoDB with what I am trying to update / insert, but I was hoping there might be something already in pymongoor something that I could use for this .

+4
source share
2 answers

replace_one .

for hostname, services in dataset[0].items():
    db.titleHardware.replace_one({'hostname':hostname},
                                 {'hostname':hostname,
                                  services.keys()[0]: services.values()[0]}, 
                                 True)
+3

mongodb updateOne? , $set:

for hostname, services in dataset[0].items():
    db.titleHardware.update_one({'hostname':hostname},
                                {'$set': {services.keys()[0]: services.values()[0]}}, 
                                upsert=True)
+1

Source: https://habr.com/ru/post/1663561/


All Articles