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)
相关推荐
梨落秋霜7 小时前
Python入门篇【文件处理】
android·java·python
Java 码农7 小时前
RabbitMQ集群部署方案及配置指南03
java·python·rabbitmq
张登杰踩9 小时前
VIA标注格式转Labelme标注格式
python
Learner9 小时前
Python数据类型(四):字典
python
odoo中国10 小时前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按
Jelena1577958579210 小时前
Java爬虫api接口测试
python
踩坑记录11 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
诸神缄默不语12 小时前
Python处理Word文档完全指南:从基础到进阶
python
海棠AI实验室12 小时前
第四章 项目目录结构:src/、configs/、data/、tests/ 的黄金布局
python·项目目录结构
爱笑的眼睛1113 小时前
超越可视化:降维算法组件的深度解析与工程实践
java·人工智能·python·ai