【MongoDB】跨库跨表查询(python版)

MongoDB跨表跨库查询

讲一个简单的例子,python连接mongodb做跨表跨库查询的正确姿势

1.数据准备:

复制代码
use order_db;
db.createCollection("orders");
db.orders.insertMany(
    [
  {
    "_id": 1,
    "order_number": "ORD123",
    "product": "Laptop",
    "customer_id": 101
  },
  {
    "_id": 2,
    "order_number": "ORD124",
    "product": "Smartphone",
    "customer_id": 102
  },
  {
    "_id": 3,
    "order_number": "ORD125",
    "product": "Tablet",
    "customer_id": 103
  }
]
    )

use customer_db;
db.createCollection("customers");
db.customers.insertMany(
    [
  {
    "_id": 101,
    "name": "John Doe",
    "email": "john@example.com",
    "address": "123 Main St"
  },
  {
    "_id": 102,
    "name": "Jane Smith",
    "email": "jane@example.com",
    "address": "456 Oak Ave"
  },
  {
    "_id": 103,
    "name": "Bob Johnson",
    "email": "bob@example.com",
    "address": "789 Pine Blvd"
  }
]
    );

2.跨集合查询

python 复制代码
from pymongo import MongoClient

## Joint Table Quety
# 连接到 MongoDB 数据库
client = MongoClient("mongodb://admin:admin@localhost:27017/")

# 选择数据库和集合
db_orders = client.order_db.orders
db_customers = client.customer_db.customers

# 执行跨表查询
pipeline = [
    {
        "$lookup": {
            "from": "customers",
            "localField": "customer_id",
            "foreignField": "_id",
            "as": "customer_info"
        }
    },
    {
        "$unwind": "$customer_info"
    },
    {
        "$project": {
            "_id": 1,
            "order_number": 1,
            "product": 1,
            "customer_info.name": 1,
            "customer_info.email": 1
        }
    }
]

result = list(db_orders.aggregate(pipeline))

# 打印结果
for order in result:
    print(order)

分析:

经过代码测试会发现,pipeline走到lookup结束,customer_info为空,lookup是作用于单个数据库下的不同集合之间的联合查询,但不支持跨库,而网络上充斥着所谓支持跨库查询的案例。。。

因此,将collection放于同一个db下,发现结果符合预期。

3.跨库查询

应该怎么做?

思考:想象我们做的业务,通常都是模块化的,之间都是通过服务/应用层接口调用来实现的,其底层正对应着不同的数据库。比如常见的订单系统和用户系统,因为集中式管理(单个数据库)容易造成性能瓶颈,会按业务进行合理拆分,也更容易复用和拓展。

所以,所谓的跨库查询,实际上就跟业务之间的通信是类似的,这里并不是单库下的主外键查询问题,而是实际场景中多库下多个服务之间的数据互通与一致性查询问题,一般处理手段是将一些联合查询问题放到业务层解决,当然,针对做不同数据库的相同表做同步复制也是可以的,不过显然这与业务拆分的初衷相违背了。

以下是简单的sample,样例数据保持不变:

python 复制代码
from pymongo import MongoClient

## Cross Database Query

# 连接到 MongoDB 数据库
client_db1 = MongoClient("mongodb://admin:admin@localhost:27017/")
client_db2 = MongoClient("mongodb://admin:admin@localhost:27017/")

# 选择数据库和集合
customer_db = client_db1.customer_db
order_db = client_db2.order_db

customers_collection = customer_db.customers
orders_collection = order_db.orders

# 查询 orders 数据
orders_data = list(orders_collection.find())
# 查询 customers 数据
customers_data_dict = {customer["_id"]: customer for customer in customers_collection.find()}
# 手动关联数据
result = []
for order in orders_data:
    customer_id = order.get("customer_id")
    # 在 customers 数据中查找匹配的 customer_id
    matching_customer = customers_data_dict.get(customer_id)
    if matching_customer:
        # 合并数据
        merged_data = {**order, "customer_info": matching_customer}
        result.append(merged_data)

# 打印结果
for item in result:
    print(item)

结果符合预期:

相关推荐
wgyang20166 分钟前
我的第一个LangFlow工作流——复读机
python
Zhen (Evan) Wang13 分钟前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya18 分钟前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
赶紧去巡山43 分钟前
pyhton基础【23】面向对象进阶四
python
旷世奇才李先生1 小时前
PyCharm 安装使用教程
ide·python·pycharm
飞翔的佩奇1 小时前
Java项目:基于SSM框架实现的忘忧小区物业管理系统【ssm+B/S架构+源码+数据库+毕业论文+开题报告】
java·数据库·mysql·vue·毕业设计·ssm框架·小区物业管理系统
这里有鱼汤1 小时前
“对象”?对象你个头!——Python世界观彻底崩塌的一天
后端·python
尘浮7282 小时前
60天python训练计划----day59
开发语言·python
wh39332 小时前
使用Python将PDF转换成word、PPT
python·pdf·word
船长@Quant2 小时前
数学视频动画引擎Python库 -- Manim Voiceover 语音服务 Speech Services
python·数学·manim·动画引擎·语音旁白