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)
相关推荐
小白银子1 小时前
零基础从头教学Linux(Day 52)
linux·运维·服务器·python·python3.11
AAA小肥杨3 小时前
基于k8s的Python的分布式深度学习训练平台搭建简单实践
人工智能·分布式·python·ai·kubernetes·gpu
lichong9514 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
Tiny番茄4 小时前
31.下一个排列
数据结构·python·算法·leetcode
小白学大数据5 小时前
实战:Python爬虫如何模拟登录与维持会话状态
开发语言·爬虫·python
FriendshipT5 小时前
目标检测:使用自己的数据集微调DEIMv2进行物体检测
人工智能·pytorch·python·目标检测·计算机视觉
平谷一勺6 小时前
数据清洗-缺失值的处理
python·数据分析
末世灯光6 小时前
时间序列入门第一问:它和普通数据有什么不一样?(附 3 类典型案例)
人工智能·python·机器学习·时序数据
开心-开心急了6 小时前
Flask入门教程——李辉 第一、二章关键知识梳理(更新一次)
后端·python·flask
锦***林6 小时前
用 Python 写一个自动化办公小助手
开发语言·python·自动化