使用 pymongo 仅从 mongodb 中查找特定键
Find only specific key from mongodb using pymongo
我已经编写了这段代码,我只想检查一个名为 Virtual_Machines
的密钥。我有以下形式的数据。我只想检查Virtual_Machines
是否存在然后不要再次上传数据。
{
"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
}
}
},
我的代码是,但输出为 None
。
db = client['Audit']
vms = db['virtual_machine']
vm = json.dumps(vm)
vmachine = vms.find_one({"Virtual_Machine"},{'_id':0})
print(vmachine)
find_one()
中的第一个参数必须是 dict
。您收到错误是因为您传递了 {"Virtual_Machine"}
,python 将其解释为 set
https://docs.python.org/3/library/stdtypes.html#set
如果要检查某个键是否存在,而不考虑其值,请使用 $exists
运算符。 https://www.mongodb.com/docs/manual/reference/operator/query/exists/
vms.find_one({'Virtual_Machines': {'$exists': True}}, {'_id':0})
我已经编写了这段代码,我只想检查一个名为 Virtual_Machines
的密钥。我有以下形式的数据。我只想检查Virtual_Machines
是否存在然后不要再次上传数据。
{
"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
}
}
},
我的代码是,但输出为 None
。
db = client['Audit']
vms = db['virtual_machine']
vm = json.dumps(vm)
vmachine = vms.find_one({"Virtual_Machine"},{'_id':0})
print(vmachine)
find_one()
中的第一个参数必须是 dict
。您收到错误是因为您传递了 {"Virtual_Machine"}
,python 将其解释为 set
https://docs.python.org/3/library/stdtypes.html#set
如果要检查某个键是否存在,而不考虑其值,请使用 $exists
运算符。 https://www.mongodb.com/docs/manual/reference/operator/query/exists/
vms.find_one({'Virtual_Machines': {'$exists': True}}, {'_id':0})