仅使用Pymongo从MongoDB找到特定键
我已经编写了此代码,只想检查一个名为 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
}
}
},
我的代码是,但是它将输出作为无
。
db = client['Audit']
vms = db['virtual_machine']
vm = json.dumps(vm)
vmachine = vms.find_one({"Virtual_Machine"},{'_id':0})
print(vmachine)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
find_one()
中的第一个参数必须是dict
。您正在遇到错误,因为您正在传递{“ virtual_machine”}
python将其解释为set
https://docs.python.org/3/library/stdtypes.html#setIf you want to check that a key exists or not ,无论其价值如何,都使用
$存在
运算符。The first parameter in
find_one()
must be adict
. You are getting your error because you are passing{"Virtual_Machine"}
which python interprets as aset
https://docs.python.org/3/library/stdtypes.html#setIf 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/