简体   繁体   English

使用 pymongo 仅从 mongodb 中查找特定密钥

[英]Find only specific key from mongodb using pymongo

I have written this code and I want to check only for a key named Virtual_Machines .我已经编写了这段代码,我只想检查一个名为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是否存在然后不要再次上传数据。

  {
          "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 .我的代码是,但它的输出为None

db = client['Audit']
vms = db['virtual_machine']
vm = json.dumps(vm)
vmachine = vms.find_one({"Virtual_Machine"},{'_id':0})    

print(vmachine)

The first parameter in find_one() must be a dict . find_one()中的第一个参数必须是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您收到错误是因为您传递了{"Virtual_Machine"} ,python 将其解释为一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.如果要检查键是否存在,无论其值如何,请使用$exists运算符。 https://www.mongodb.com/docs/manual/reference/operator/query/exists/ https://www.mongodb.com/docs/manual/reference/operator/query/exists/

vms.find_one({'Virtual_Machines': {'$exists': True}}, {'_id':0})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM