python实现数据库两个表之间的更新操作(模糊匹配)示例

复制代码
from pymongo import MongoClient
import pandas as pd


# 连接到MongoDB(这里假设MongoDB运行在本地默认端口上)
mgclient = MongoClient('localhost', 27017)

# 选择数据库(如果你没有指定数据库,MongoDB会使用默认的'test'数据库)
db = mgclient['test']  # 替换'your_database_name'为你的数据库名
test1_collection=db["test1"].find({})
test1_list=list(test1_collection)
test2_collection=db["test2"].find({})
test2_list=list(test2_collection)

# 这种方式只适合插入存在的数据。
for document1 in test1_list:
    document1.pop("_id")
    document1["codename"]=document1["code"]
    # document1["codename"] = document1["code"]
    for document2 in test2_list:
        # dataframe包含关系不是很好merge
        if document1["code"]==document2["code"] and document1["code"].startswith(document2["code"]):
            document1["codename"]=document2["name"]
            print(document1)
            # 如果只用写入能够匹配上的,在这里insert
            # db["test3"].insert_one(document1)
    db["test3"].insert_one(document1)
相关推荐
多恩Stone1 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
XW01059991 小时前
4-11判断素数
前端·python·算法·素数
深蓝电商API1 小时前
爬虫增量更新:基于时间戳与哈希去重
爬虫·python
两万五千个小时1 小时前
构建mini Claude Code:06 - Agent 如何「战略性遗忘」(上下文压缩)
人工智能·python
两万五千个小时2 小时前
构建mini Claude Code:12 - 从「文件冲突」到「分身协作」:Worktree 如何让多 Agent 安全并行
人工智能·python·架构
yuki_uix2 小时前
为什么我的 Auth Token 藏在了 Network 面板的 Doc 里?
前端·python·debug
甲枫叶2 小时前
【claude+weelinking产品经理系列16】数据可视化——用图表讲述产品数据的故事
java·人工智能·python·信息可视化·产品经理·ai编程
番茄去哪了3 小时前
Python基础入门(二)
linux·服务器·开发语言·python
未来之窗软件服务3 小时前
AI人工智能(二十一)pt模型转onnx sensvoice—东方仙盟练气期
人工智能·python·仙盟创梦ide·东方仙盟
柒.梧.4 小时前
Java构造器精讲:从基础特征到权限修饰符
开发语言·python