I have written this code and I want to check only for a key named Virtual_Machines
. I have data in the following form. I only want to check if Virtual_Machines
is there then don't upload data again.
{
"Virtual_Machines": {
"Debian": {
"VM_Name": "Debian",
"VM_Location": "eastus",
"VM_Disk_Name": "Debian_OsDisk_1_b890f5f5c42647549c881c0706b85201",
"VM_Publisher_Info": {
"publisher": "debian",
"offer": "debian-11",
"sku": "11-gen2",
"version": "latest"
},
"Vm_Disk_Type": "Standard_D2s_v3",
"VM_Encryption": null
},
"Ubuntu": {
"VM_Name": "Ubuntu",
"VM_Location": "eastus",
"VM_Disk_Name": "Ubuntu_disk1_0610e0fde49b481490ef0a069a03b460",
"VM_Publisher_Info": {
"publisher": "canonical",
"offer": "0001-com-ubuntu-server-focal",
"sku": "20_04-lts-gen2",
"version": "latest"
},
"Vm_Disk_Type": "Standard_D2s_v3",
"VM_Encryption": null
}
}
},
My code is but it is giving output as None
.
db = client['Audit']
vms = db['virtual_machine']
vm = json.dumps(vm)
vmachine = vms.find_one({"Virtual_Machine"},{'_id':0})
print(vmachine)
CodePudding user response:
The first parameter in find_one()
must be a dict
. You are getting your error because you are passing {"Virtual_Machine"}
which python interprets as a set
https://docs.python.org/3/library/stdtypes.html#set
If you want to check that a key exists or not, regardless of its value, use the $exists
operator. https://www.mongodb.com/docs/manual/reference/operator/query/exists/
vms.find_one({'Virtual_Machines': {'$exists': True}}, {'_id':0})