【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)

结果符合预期:

相关推荐
云泽野10 分钟前
【Java|集合类】list遍历的6种方式
java·python·list
IMPYLH2 小时前
Python 的内置函数 reversed
笔记·python
计算机毕设定制辅导-无忧学长3 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
小赖同学啊4 小时前
物联网数据安全区块链服务
开发语言·python·区块链
程序员柳4 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
码荼4 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud
梦在深巷、4 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb
IT乌鸦坐飞机4 小时前
ansible部署数据库服务随机启动并创建用户和设置用户有完全权限
数据库·ansible·centos7
IT_10244 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
小陈phd5 小时前
李宏毅机器学习笔记——梯度下降法
人工智能·python·机器学习