【问题标题】:Retrieve the last n days from MongoDB file using Python使用 Python 从 MongoDB 文件中检索最近 n 天
【发布时间】:2021-04-13 08:34:26
【问题描述】:

下面的代码连接到 MongoDB 数据库并选择指定的 JSON 文件,将其展平并将其导出为 CSV。

所以我的问题是 MongoDB 数据库中的一些 JSON 文件绝对庞大,有数千行,所以我想做的是过滤 table 向下,以便我只引入过去 7 天的数据。

from pymongo import MongoClient
import pandas as pd
import os, uuid, sys
import collections
from azure.storage.filedatalake import DataLakeServiceClient
from azure.core._match_conditions import MatchConditions
from azure.storage.filedatalake._models import ContentSettings
from pandas import json_normalize


mongo_client = MongoClient("connstring")
db = mongo_client.nhdb
table = db.Report

document = table.find()

mongo_docs = list(document)
mongo_docs = json_normalize(mongo_docs)

mongo_docs.to_csv("Report.csv", sep = ",", index=False) 

任何帮助将不胜感激。

注意:我知道使用下面的表达式在 Azure 数据工厂中执行此操作的方法,但是,我不确定如何在 Python 中执行此操作

{"createdDatetime":{$gt: ISODate("@{adddays(utcnow(),-7)}")}}

【问题讨论】:

    标签: python json filter pymongo


    【解决方案1】:

    在python中创建一个日期时间对象作为过滤器;例如,这显示了过去 7 天:

    from datetime import datetime, timedelta
    document = table.find({'createdDatetime': {'$gt': datetime.utcnow() - timedelta(days=7)}})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 2021-01-16
      • 2017-07-18
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 2018-07-22
      相关资源
      最近更新 更多