首页 > 解决方案 > MongoDB数据清洗聚合管道

问题描述

我花了一些时间从我的 pandas 数据库中清理数据,现在想将我在 pandas 中所做的应用到实际的数据库中。

我的文档结构如下,清洗的重点是内容字段:

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

重点在内容领域,清洗聚合管道需要做四件事:

要删除 pandas 中的空值,我运行了以下命令:

articles.dropna(subset=['content'], inplace=True)

在 Mongo 中,我运行了以下命令:

db.Articles.deleteMany({'content': {'$type': 10}})

这行得通,所以管道的这一部分得到了照顾(我认为)。

要删除 pandas 中的重复项,我运行了以下命令:

articles.drop_duplicates(subset=['content'], inplace = True)

我怎样才能在mongo中做同样的事情?

删除包含 html 标签的文档以及一些我不想要的字符串。我在熊猫中运行了以下代码:

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)

我将如何在 Mongo 中做同样的事情?

最后,我可以通过运行以下命令删除不包含关键字的文章:

relevant_words = ['Bitcoin', 'bitcoin', 'Ethereum', 'ethereum', 'Tether', 'tether', 'Cardano', 'cardano', 'XRP', 'xrp']
articles['content'] = articles['content'][articles['content'].str.contains('|'.join(relevant_words))].str.lower()
articles.dropna(subset=['content'], inplace=True)

上面的所有代码都用于清理 pandas 中的数据。现在我想将它们应用到实际的数据库中。我需要帮助构建聚合管道以获得所需的结果。我也对其他选择持开放态度。

任何帮助将不胜感激。

标签: python-3.xpandasmongodbdata-cleaningmongodb-atlas

解决方案


推荐阅读