使用PyMongo查询嵌套JSON中的特定值

时间:2019-03-07 17:53:57

标签: python mongodb pymongo

我的JSON如下:

# Example static JSON payload
request = {"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

我要使用PyMongo与menuitem一起获得"value" : "New"

当前,我尝试了request = {'query': {"menuitem.value": "New"}},并以request的身份发送了此requests.get(url, json=request)

在服务器端,我正在通过

执行查询

cursor = mongo.db[collection_name].find(query)

现在,这将返回一个空值{}

但是,当我以

发送查询时

request = {'query': {"menu.popup.menuitem.value": "New"}}

它返回

{'_id': '5c815445d866fc261c400e88',
 'menu': {'id': 'file',
          'popup': {'menuitem': [{'onclick': 'CreateNewDoc()', 'value': 'New'},
                                 {'onclick': 'OpenDoc()', 'value': 'Open'},
                                 {'onclick': 'CloseDoc()', 'value': 'Close'}]},
          'value': 'File'}}

如何仅通过menuitem获得'value':'New'记录?

2 个答案:

答案 0 :(得分:0)

我不确定pymongo。但是我可以过滤“请求”以获得所需的“值”。

由于它是一个“列表”,因此您可以遍历“ menuitem”键。

result=request['menu']['popup']['menuitem']
for i in range(len(result)):
   print result[i]["value"]
New
Open
Close

答案 1 :(得分:0)

您可以使用以下查询投影来过滤结果:

from pymongo import MongoClient
from pprint import pprint

client = MongoClient(port=27017)
db = client.sodb1
# Step 2: Create sample data
request = {"menu": {
    "id": "file",
    "value": "File",
    "popup": {
        "menuitem": [
            {"value": "New", "onclick": "CreateNewDoc()"},
            {"value": "Open", "onclick": "OpenDoc()"},
            {"value": "Close", "onclick": "CloseDoc()"}
        ]
    }
}}

db.socoll1.insert_one(request)

# Get entire Doc
cursor = db.socoll1.find({"menu.popup.menuitem.value": "New"})

print('\nEntire Doc is\n')
for doc in cursor:
    pprint(doc)

# add the filter to the projection
cursor = db.socoll1.find({"menu.popup.menuitem.value": "New"}, {"menu.popup.menuitem.$": 1})

print('\nJust what you want is\n')
for doc in cursor:
    pprint(doc)


#outputs
Entire Doc is

{'_id': ObjectId('5c817bf1dbb08c1b51f54d7e'),
 'menu': {'id': 'file',
          'popup': {'menuitem': [{'onclick': 'CreateNewDoc()', 'value': 'New'},
                                 {'onclick': 'OpenDoc()', 'value': 'Open'},
                                 {'onclick': 'CloseDoc()', 'value': 'Close'}]},
          'value': 'File'}}

Just what you want is

{'_id': ObjectId('5c817bf1dbb08c1b51f54d7e'),
 'menu': {'popup': {'menuitem': [{'onclick': 'CreateNewDoc()',
                                  'value': 'New'}]}}}