微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从mongodb中的嵌套文档中查询数据?

如何解决如何从mongodb中的嵌套文档中查询数据?

我在此嵌套文档中工作过多。我尝试阅读该文档,并遵循其他SO响应以查看它是否对我有用,但是我没有得到想要的结果。我想从一个大的嵌套文档中提取一些信息。

数据

我已将数据上传到mongo游乐场。 https://mongoplayground.net/p/7nbLtXMlFMx

{"_id":{"$oid":"5f7f29259ac5883ec5eed1ec"},"name":"Walmart","page":{"name":"body","config":{},"children":[{"name":"company-title","config":{"title":"Walmart","rank":"1","franchiseTitle":"Fortune 500","franchisePermalink":"https://fortune.com/fortune500/2020/","parentPermalink":"https://fortune.com/company/walmart/"},"children":[]},{"name":"company-single-pagination","config":{"prevName":"","prevLink":"","prevRank":"","nextName":"Amazon.com","nextLink":"https://fortune.com/company/amazon-com/fortune500/","nextRank":2,"hideRanking":false,"franchiseTitle":"Fortune 500"},{"name":"company-hero","config":{"description":"After years of investment in its technology and stores,Walmart has indisputably emerged as a strong No. 2 to Amazon in U.S. e-commerce,with sales up 37% last year. But as the initial weeks of the novel coronavirus pandemic have shown,Walmart’s 4,600 U.S. stores have proved to be an effective weapon by allowing curbside pickup for online orders at a time shoppers want to limit time in stores—but still want their orders quickly. That sentiment is not likely to change anytime soon. Walmart Inc.’s Sam’s Club is finding renewed energy,too. Walmart is benefiting from focusing on select overseas markets,such as India and China,rather than competing everywhere."},"children":[{"name":"brightcove-video","config":{"accountId":"2111767321001","disableAds":false,"disableAutoplay":false,"disableContinuousPlay":false,"disableViewplay":false,"isLeadVideo":false,"loop":false,"playerId":"HDNR3TkSj","stickyPlayerOff":false,"silentlyAutoplay":true,"videoId":{"$numberLong":"6156999393001"},"section":""},"children":[]}]},{"name":"company-about-wrapper","children":[{"name":"company-additional-media",{"name":"advertising-slot","config":{"align":"center","lazyload":true,"useDynamicChannel":true,"placementName":"InStream","slotId":"InStream0","targeting":{"placement_name":"InStream","index":1}},{"name":"company-information","config":{"title":"Company information","country":"U.S.","headquarters":"Bentonville,Ark.","industry":"General Merchandise","ceo":"C. Douglas McMillon","website":"https://www.stock.walmart.com","companyType":"Public","ticker":"WMT","revenues":"523964","profits":"14881","marketValue":"389244","employees":"2200000","updated":"9/21/20","footnote":"Market value as of Sept. 15,2020."},"slotId":"InStream1","index":2}},{"name":"company-table-wrapper","children":[{"name":"company-data-table","config":{"title":"Key Financials (Last Fiscal Year)","tableIndex":0,"table":{"franchiseId":2814606,"title":"Key Financials (Last Fiscal Year)","rows":[{"value":"Revenues ($M)","pctChange":"Revenue Percent Change"},{"value":"Profits ($M)","pctChange":"Profits Percent Change"},{"value":"Assets ($M)"},{"value":"Total Stockholder Equity ($M)"}],"showValue":"show_value","valueHeader":"$ millions","showPctChange":"show_pct_change","pctChangeHeader":"% change"},"updated":"","data":[{"key":"f500_revenues","value":"523964","fieldMeta":{"franchiseId":2814606,"title":"Revenues ($M)","altTitle":"Revenues ($M)","description":"Companies are ranked by total revenues for their respective fiscal years.","type":"Money","saveIn":"post_Meta","importField":"f500_revenues","sortable":"sortable","order":"desc"}},{"key":"f500_profits","value":"14881","title":"Profits ($M)","altTitle":"Profits ($M)","description":"Net income after extraordinary charges for a company's respective fiscal year.","decimals":"1","importField":"f500_profits",{"key":"assets","value":"236495","title":"Assets ($M)","altTitle":"Assets ($M)","description":"Total assets on a company's fiscal year-end balance sheet.","importField":"assets",{"key":"totshequity","value":"74669","title":"Total Stockholder Equity ($M)","importField":"totshequity"}}],"footnote":"","themeName":"half","change":[{"key":"revchange","value":"1.9","title":"Revenue Percent Change","altTitle":"Revenue Change","description":"Increase/decrease in revenues between the current and prior fiscal years.","type":"Percent","importField":"revchange",{"key":"prftchange","value":"123.1","title":"Profits Percent Change","altTitle":"Profit Change","description":"Increase/decrease in profits between the current and prior fiscal years.","importField":"prftchange",{"key":null,"value":"","fieldMeta":false},"fieldMeta":false}],"changeHeader":"% change","showChange":true},{"name":"company-data-table","config":{"title":"Profit Ratios","tableIndex":1,"title":"Profit Ratios","rows":[{"value":"Profit as % of Revenues"},{"value":"Profits as % of Assets"},{"value":"Profits as % of Stockholder Equity"}],"data":[{"key":"prftpctsls","value":"2.8","title":"Profit as % of Revenues","importField":"prftpctsls"}},{"key":"prftpctasts","value":"6.3","title":"Profits as % of Assets","importField":"prftpctasts"}},{"key":"prftpctseqty","value":"19.9","title":"Profits as % of Stockholder Equity","importField":"prftpctseqty"}}],"change":[{"key":null,"valueHeader":"","showChange":false},"config":{"title":"Earnings Per Share (Last Fiscal Year)","tableIndex":2,"title":"Earnings Per Share (Last Fiscal Year)","rows":[{"value":"Earnings Per Share ($)"},{"value":"EPS % Change (from 2018)"},{"value":"EPS % Change (5 year annual rate)"},{"value":"EPS % Change (10 year annual rate)"}],"data":[{"key":"eps","value":"5.19","title":"Earnings Per Share ($)","altTitle":"EPS","type":"Number","decimals":"2","importField":"eps"}},{"key":"epschange","value":"129.6","title":"EPS % Change (from 2018)","importField":"epschange"}},{"key":"eps5yr","value":"0.5","title":"EPS % Change (5 year annual rate)","importField":"eps5yr"}},{"key":"eps10yr","value":"3.4","title":"EPS % Change (10 year annual rate)","importField":"eps10yr"}}],"config":{"title":"Total Return","tableIndex":3,"title":"Total Return","rows":[{"value":"Total Return to Investors (2019)"},{"value":"Total Return to Investors (5 year,annualized)"},{"value":"Total Return to Investors (10 year,annualized)"}],"data":[{"key":"totrti","value":"30.3","title":"Total Return to Investors (2019)","importField":"totrti"}},{"key":"totrti5yr","value":"9.4","title":"Total Return to Investors (5 year,annualized)","importField":"totrti5yr"}},{"key":"totrti10yr","value":"11","title":"Total Return to Investors (10 year,"importField":"totrti10yr"}}],{"name":"company-qlik","config":{"title":"Take a unique journey through the F500","eyebrowLabel":"fortune + qlik","description":"<p>We teamed up with Qlik,the Official Analytics Partner of the Fortune 500,to bring to life the shifting fortunes of iconic companies and sectors in an interactive data visualization.</p>\n","link":"https://qlik.fortune.com/"},"children":[{"name":"image","config":{"aspectRatio":0.6666666666666666,"attachmentId":2862622,"alt":"","caption":"","crops":[],"height":300,"imageSize":"qlik_2x3","lqipSrc":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif?quality=60&resize=60,40","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"resize":[181,296]}}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif","srcset":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif?resize=362,592 0w,https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif?resize=181,296 0w","url":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif","useBasicImg":false,"usingDataFallback":false,"width":200,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"100vw"},{"name":"image","config":{"aspectRatio":1.5,"attachmentId":2862623,"height":200,"imageSize":"qlik_3x2","lqipSrc":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif?quality=60&resize=60,90",121]}}],"src":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif","srcset":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif?resize=362,242 0w,https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif?resize=181,121 0w","url":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif","width":300,{"name":"company-rank-history-wrapper","children":[{"name":"company-interactives-wrapper","children":[{"name":"interactive","config":{"heading":"Walmart Rank History","interactiveUrl":"https://interactives.fortune.com/f500-dataviz-2020/rank_chart_single_co/index.html?guid=2255","refinitivUrl":"https://interactives.fortune.com/f500-dataviz-2020/rank_chart_single_co/index.html?ric","themeName":"company"},"children":[]}]}]},{"name":"company-historical","config":{"franchiseId":2814606,"companyId":2818204},{"name":"sidebar","config":{"themeName":"right"},"children":[{"name":"company-data-store-cta","config":{"buttonText":"Purchase Now","text":"Leads,insights,and financial data for the FORTUNE 500,FORTUNE 1000,and Global 500 companies.","url":"/data-store/"},"useDynamicChannel":false,"placementName":"RightRailFlex","slotId":"RightRailFlex0","targeting":{"placement_name":"RightRailFlex",{"name":"company-ranking-list","config":{"heading":"Lists ranking","title":"Walmart"},"children":[{"name":"company-ranking-list-item","config":{"title":"Change the World","permalink":"https://fortune.com/company/walmart/change-the-world/","excerpt":"As we face unprecedented collective challenges,cooperation has become a business superpower.","year":"2020","color":"#f3eee2","logo":"","rank":"9","itemId":2818204},"config":{"aspectRatio":false,"attachmentId":2885302,"height":1920,"imageSize":"franchise-logo","lqipSrc":"data: image/gif;base64,"transforms":{"w":[115]},"descriptor":115}],"src":"https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-logo2-1.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-logo2-1.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-logo2-1.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-logo2-1.jpg","width":2880,"sizes":"115px"},{"name":"company-ranking-list-item","config":{"title":"Global 500","permalink":"https://fortune.com/company/walmart/global500/","excerpt":"This year's Global 500 generated $33.3 trillion in revenues and $2.1 trillion in profits.","color":"#ffe500","attachmentId":2864400,"alt":"G500-Featured Image-logo-2020","src":"https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-logo-2020.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-logo-2020.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-logo-2020.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-logo-2020.jpg","config":{"title":"Fortune 500","permalink":"https://fortune.com/company/walmart/fortune500/","excerpt":"This year's Fortune 500 marks the 66th running of the list.","color":"#000000","attachmentId":2817676,"alt":"F500-2020-logo","src":"https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-logo.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-logo.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-logo.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-logo.jpg","config":{"title":"World’s Most Admired Companies","permalink":"https://fortune.com/worlds-most-admired-companies/2020/walmart/","excerpt":"For an astounding 13th straight year,Apple claims the top spot in Fortune’s annual ranking of corporate reputation,based on a survey of almost 3,800 executives,directors,and analysts.","rank":"18","itemId":2753766},"attachmentId":2757757,"height":356,"src":"https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg","width":536,{"name":"company-latest-news-wrapper","config":{"title":"Latest news for Walmart"},"children":[{"name":"advertising-slot","slotId":"InStream2","index":3}},{"name":"company-latest-news","children":[{"name":"content-item","config":{"themeName":"company_latest_news","timeago":"","isNativoTout":false,"eyebrowSectionLabel":"Conferences","eyebrowSectionLink":"https://fortune.com/section/conferences/","eyebrowTagLabel":"Most Powerful Women","eyebrowTagLink":"https://fortune.com/tag/most-powerful-women/","title":"How Sam’s Club helped small businesses through COVID","permalink":"https://fortune.com/2020/10/01/sams-club-ceo-kathryn-mclay-small-business-most-powerful-women/","id":2894934,"excerpt":"The pandemic has sped up tech innovation at the warehouse retailer.","publishDateIso8601":"2020-10-01T16:53:55-04:00","type":"post"},"config":{"aspectRatio":0.5625,"attachmentId":2891872,"height":0,"imageSize":"full","postId":2894934,"sources":[],"src":"","srcset":"","url":"","width":0},{"name":"byline","config":{"link":"https://fortune.com/author/phil-wahba/","name":"Phil Wahba"},{"name":"content-item","eyebrowSectionLabel":"Retail","eyebrowSectionLink":"https://fortune.com/section/retail/","eyebrowTagLabel":"Walmart","eyebrowTagLink":"https://fortune.com/tag/walmart/","title":"Walmart unveils new store design inspired by Amazon and airports","permalink":"https://fortune.com/2020/09/30/walmart-new-store-design-app-online-pickup-amazon-airports/","id":2893828,"excerpt":"The discount chain wants people to use its Walmart app more and to be able to get in and out faster.","publishDateIso8601":"2020-09-30T11:41:27-04:00","attachmentId":2893884,"postId":2893828,"eyebrowTagLabel":"MPW Summit","eyebrowTagLink":"https://fortune.com/tag/mpw-summit/","title":"3 ways Walmart and Home Depot execs think retail will change for good","permalink":"https://fortune.com/2020/09/29/retail-coronavirus-pandemic-home-depot-walmart-execs-covid-19/","id":2893036,"excerpt":"We won't go back to pre-pandemic behavior,top execs from Walmart and Home Depot predicted at Fortune's virtual Most Powerful Women's conference Tuesday. ","publishDateIso8601":"2020-09-29T18:12:00-04:00","attachmentId":2890633,"postId":2893036,"config":{"link":"https://fortune.com/author/anne-sraders/","name":"Anne Sraders"},"eyebrowSectionLabel":"Environment","eyebrowSectionLink":"https://fortune.com/section/environment/","title":"Walmart says it will eliminate emissions from global operations by 2040","permalink":"https://fortune.com/2020/09/21/walmart-emissions-global-reduction/","id":2888827,"excerpt":"The cuts,while substantial,will only cover its own operation's emissions—5% of the total. ","publishDateIso8601":"2020-09-21T06:52:56-04:00","attachmentId":2888833,"postId":2888827,"config":{"link":"https://fortune.com/author/stephen-stapczynski/","name":"Stephen Stapczynski"},"config":{"link":"https://fortune.com/author/akshat-rathi/","name":"Akshat Rathi"},"config":{"link":"https://fortune.com/author/bloomberg/","name":"Bloomberg"},"eyebrowTagLabel":"Food Waste","eyebrowTagLink":"https://fortune.com/tag/food-waste/","title":"Exclusive: Startup Apeel is launching ‘plastic-free’ cucumbers at Walmart to cut back on waste","permalink":"https://fortune.com/2020/09/21/apeel-cucumbers-walmart-plastic-food-waste/","id":2888394,"excerpt":"Apeel’s English cucumbers are coated in a plant-based material that extends shelf life without the need for single-use plastic.","publishDateIso8601":"2020-09-21T06:00:31-04:00","attachmentId":2888387,"postId":2888394,"config":{"link":"https://fortune.com/author/beth-kowitt/","name":"Beth Kowitt"},{"name":"company-latest-videos","config":{"tags":["Walmart"],"slotId":"RightRailFlex1","children":[]}]}]}]}}

我要提取的是config中的children of page,其中名称company-information名称中的description来自company-hero。我阅读了文章和文档,并且如果文档不那么嵌套,我可以做我想做的事情。但是我完全迷失了如何提取我正在寻找的信息。在这种程度上,这是我第一次在Mongodb上工作。我以前做过非常基础的事情。

我尝试过

db.collection.find(
    {"page.children.3.children.2.name": {"$eq": "company-information"}},{"page.children.3.children.2": 1}
) 

但结果为空

输出

大约有1000行(?不知道我是否可以称其行)。我感兴趣的部分是提取名称page.children[3].children[2]的{​​{1}}。因此结果应为以下内容

company-information

解决方法

使用汇总查询,您可以(几乎!)执行任何操作。对于您的情况,我建议使用$unwind将列表转换为对象,然后在目标字段上使用$match,用$project缩小输出,用$replaceRoot简化结构,$limit很好,因为实际上有2条符合您条件的记录。

https://mongoplayground.net/p/UsKeqA0aWYK

db.collection.aggregate([
  {
    "$unwind": "$page.children"
  },{
    "$unwind": "$page.children.children"
  },{
    "$match": {
      "page.children.children.name": "company-information"
    }
  },{
    "$project": {
      "_id": 0,"page.children.children.config": 1
    }
  },{
    "$replaceRoot": {
      "newRoot": "$page.children.children"
    }
  },{
    "$limit": 1
  }
])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?