from pymongo import MongoClient

# Connect to MongoDB
# client = MongoClient("mongodb://192.168.31.176:27017/")
# db = client["zerodha_test"]

client = MongoClient("mongodb://jenya:DJenya$Mongo%40St0ckDB@172.105.59.175:27017/")
db = client["trade_iq"]
collection1 = db["zerodha_instruments"]  # Collection containing DOC1
# collection2 = db["nse_data1"]  # Collection containing DOC2
collection2 = db["orders"]  # Collection containing DOC2

for name in collection2.find({}, {"_id": 0, "symbol": 1}):
    # Find all do vcuments in collection1 where tradingsymbol starts with the symbol in collection2
    docs1 = collection1.find({"tradingsymbol": {"$regex": f"^{name['symbol']}", "$options": "i"}, "exchange": "BSE", "segment": "BSE"})

    # Loop through matching docs from collection1
    for doc1 in docs1:
        tradingsymbol = doc1["tradingsymbol"]
        instrument_token = doc1["instrument_token"]
        exchange_token = doc1["exchange_token"]

        # Update matching documents in collection2 based on the symbol prefix
        result = collection2.update_many(
            {"symbol": {"$regex": f"^{tradingsymbol.split('-')[0]}", "$options": "i"}},
            {
                "$set": {
                    "instrument_token": instrument_token,
                    "exchange_token": exchange_token
                }
            }
        )

        print(f"Updated {result.modified_count} documents in collection2 for symbol {tradingsymbol}")

    print("Update process completed.")