File size: 909 Bytes
aeb70ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from pymongo import MongoClient
from bson import ObjectId
from datetime import datetime
import json
import time
import os

client = MongoClient("mongodb+srv://rivalcoder01:PurmpaRXBSThyuQA@cluster0.f7zziod.mongodb.net/?retryWrites=true&w=majority")
collection = client["test"]["products"]

EXPORT_DIR = "mongo_exports"
os.makedirs(EXPORT_DIR, exist_ok=True)

def clean(doc):
    for k, v in doc.items():
        if isinstance(v, ObjectId):
            doc[k] = str(v)
        elif isinstance(v, datetime):
            doc[k] = v.isoformat()
    return doc

def export_loop():
    while True:
        docs = list(collection.find())
        fname = f"{EXPORT_DIR}/products.jsonl"
        with open(fname, "w") as f:
            for doc in docs:
                doc = clean(doc)
                f.write(json.dumps(doc) + "\n")
        print("[Mongo Exporter] Wrote updated products.jsonl")
        time.sleep(5)