【问题标题】:Get domain name from URL in MongoDB collection从 MongoDB 集合中的 URL 获取域名
【发布时间】:2020-08-06 03:40:36
【问题描述】:

我正在尝试从 URL 字段中获取域名。目前,它作为 URL:https://google.bing.com/Jumbo-Privacy 存储在集合中。我只需要google.bing.com

对于www.google.com 的URL,我只想要google.com。无论如何,当我显示集合结果时,我是否可以直接这样做?

当我添加'domain': {'$arrayElemAt': [ { '$split': ["$url", "/"] }, 2 ] },

它可以工作并为https://google.bing.com/Jumbo-Privacy 返回google.bing.com。但仍会为其他所有内容返回 www

【问题讨论】:

    标签: mongodb mongodb-query nosql substring pymongo


    【解决方案1】:

    使用urllib.parse library 中的urlparse

    from urllib.parse import urlparse
    url = urlparse('https://google.bing.com/Jumbo-Privacy')
    print (url.netloc)
    

    给予:

    google.bing.com
    

    【讨论】:

      【解决方案2】:

      您必须编写一些自定义代码来解析它。

      这是一个例子:

      
      //Assuming you'll always have https:// infront
      
      const Url = 'https://moodli.org/geo'
      
      //Split thé URL into an array using the forward slash
      let urlSplit = Url.split('/');
      
      //Get the domain name
      let domian = urlSplit[2]
      
      
      

      【讨论】:

      • 这是 ec6 对吧?我们可以直接在MongoDB中这样做吗?
      • 是的。它是 JavaScript。是的,你可以直接用 mongodb 做到这一点。从理论上讲,您编写的查询应该可以工作。
      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多