【问题标题】:MongoDB delete data using regexMongoDB使用正则表达式删除数据
【发布时间】:2021-06-21 01:49:07
【问题描述】:

我能够使用以下内容通过 pandas 删除数据:

import re

repl = {r'<[^>]+>': '', 
        r'\r\n': ' ',
        r'Share to facebook|Share to twitter|Share to linkedin|Share on Facebook|Share on Twitter|Share on Messenger|Share on Whatsapp': ''}

articles['content'] = articles['content'].replace(repl, regex=True)

我怎样才能在 Atlas 中的实际数据库上做同样的事情?

我的数据结构是:

_id:
title:
url:
description:
author:
publishedAt:
content:
source_id:
urlToImage:
summarization:

【问题讨论】:

    标签: pandas mongodb aggregation-framework mongodb-atlas


    【解决方案1】:

    MongoDB 没有任何内置的运算符来随时随地执行正则表达式替换(目前)。

    您可以使用您选择的编程语言中的正则表达式 find 循环浏览文档,然后用这种方式替换。

    from pymongo import MongoClient
    import re
    
    
    m_client = MongoClient("<MONGODB-URI-STRING")
    db = m_client["<DB-NAME>"]
    collection = db["<COLLECTION-NAME>"]
    
    replace_dictionary = {
        r'<[^>]+>': '',
        r'\r\n': ' ',
        r'Share to facebook|Share to twitter|Share to linkedin|Share on Facebook|Share on Twitter|Share on Messenger|Share on Whatsapp': ''
    }
    
    count = 0
    
    for it in collection.find({
        # Merge all refex finds to a single list
        "$or": [{"content": re.compile(x, re.IGNORECASE)} for x in replace_dictionary.keys()]
    }, {
        # Project only the field to be replaced for faster execution of script
        "content": 1
    }):
      #  Iterate over regex and replacements and apply the same using `re.sub` 
      for k, v in replace_dictionary.items():
        it["content"] = re.sub(
            pattern=k,
            repl=v,
            string=it["content"],
        )
    
      # Update the regex replaced string
      collection.update_one({
        "_id": it["_id"]
      }, {
        "$set": {
            "content": it['content']
        }
      })
    
      # Count to keep track of completion
      count += 1
      print("\r", count, end='')
    
    print("DONE!!!")
    

    【讨论】:

    • 我将答案标记为已解决,但如果我再次运行脚本,它仍然会“删除”文档。我期待得到 0
    • 我不明白你说的删除是什么意思。该脚本不删除任何内容。它只会替换正则表达式匹配的文本并更新content 键,仅此而已。您能详细说明您面临的问题吗?
    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2011-12-23
    • 2016-04-18
    • 1970-01-01
    • 2016-07-23
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多