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)
相关推荐
yaoxin52112311 分钟前
397. Java 文件操作基础 - 创建常规文件与临时文件
java·开发语言·python
dFObBIMmai21 分钟前
MySQL主从同步中大事务导致的延迟_如何拆分大事务优化同步
jvm·数据库·python
szccyw024 分钟前
mysql如何限制特定存储过程执行权限_MySQL存储过程安全访问
jvm·数据库·python
小白学大数据30 分钟前
Python 自动化爬取网易云音乐歌手歌词实战教程
爬虫·python·okhttp·自动化
风之所往_2 小时前
Python 3.0 新特性全面总结
python
2401_882273722 小时前
如何在 CSS 中正确加载本地 JPG 背景图片
jvm·数据库·python
Lucas_coding2 小时前
【Claude Code Router】 Claude Code 兼容 OpenAI 格式 API, Claude code 接入本地部署模型
人工智能·python
测试员周周2 小时前
【AI测试系统】第5篇:从 Archon 看 AI 工程化落地:为什么"确定性编排+AI 弹性智能"是终局?
人工智能·python·测试
大飞记Python3 小时前
【2026更新】Python基础学习指南(AI版)——04数据类型
开发语言·人工智能·python
Hello eveybody4 小时前
介绍一下背包DP(Python)
开发语言·python·动态规划·dp·背包dp