python mongodb lookup关联查询

$lookup 是 Mongodb 3.2版本 新增的聚合框架中的一种查询方式; 主要用来实现多表链接查询; 相当关系型数据库中多表链接查询。

  1. 主要功能 是将每个输入待处理的文档,经过$lookup 阶段的处理,输出的新文档中会包含一个新生成的数组列(户名可根据需要命名新key的名字 )。数组列存放的数据 是 来自 被Join 集合的适配文档,如果没有,集合为空(即 为[ ])
字段 描述
from 同一个database中用于连接查询的collection的名称
localField 源集合中的match值,如果输入的集合中,某文档没有 localField这个Key(Field),在处理的过程中,会默认为此文档含有 localField:null的键值对。
foreignField 存在于from那个集合的外键
as 别名
let 定义参数,在pipeline中使用
pipeline 对join进来的数据做筛选
  1. 例子、插入orders数据
python 复制代码
import pymongo
import random
import string
from pymongo.collation import Collation
random.seed(10)
letters = string.ascii_lowercase
upper = string.ascii_uppercase


class MongoDBServer():
    def __init__(self,database,collation) -> None:
        self.client = pymongo.MongoClient('mongodb://ellis:ellischen@192.168.214.133:32000/')
        self.database = self.client[database]
        
        self.colleceion = self.database[collation]
        
    def insert_many(self,documents):
        self.colleceion.insert_many(documents)


server = MongoDBServer('lookup','orders')

server.insert_many([
   { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
   { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
   { "_id" : 3  }
] )

插入inventory数据

python 复制代码
import pymongo
import random
import string
from pymongo.collation import Collation
random.seed(10)
letters = string.ascii_lowercase
upper = string.ascii_uppercase


class MongoDBServer():
    def __init__(self,database,collation) -> None:
        self.client = pymongo.MongoClient('mongodb://ellis:ellischen@192.168.214.133:32000/')
        self.database = self.client[database]
        
        self.colleceion = self.database[collation]
        
    def insert_many(self,documents):
        self.colleceion.insert_many(documents)
        
    def lookup(self,destination,localField,foreignField,as_field):
        return self.colleceion.aggregate([{"$lookup":{"from":destination,"localField":localField,"foreignField":foreignField,"as":as_field}}])


server = MongoDBServer('lookup','inventory')

server.insert_many([
   { "_id" : 1, "sku" : "almonds", "description": "product 1", "instock" : 120 },
   { "_id" : 2, "sku" : "bread", "description": "product 2", "instock" : 80 },
   { "_id" : 3, "sku" : "cashews", "description": "product 3", "instock" : 60 },
   { "_id" : 4, "sku" : "pecans", "description": "product 4", "instock" : 70 },
   { "_id" : 5, "sku": None, "description": "Incomplete" },
   { "_id" : 6 }
] )

inventory 和orders通过item以及sku两个字段关联

  1. 使用lookup查询
python 复制代码
import pymongo
import random
import string
from pymongo.collation import Collation
random.seed(10)
letters = string.ascii_lowercase
upper = string.ascii_uppercase


class MongoDBServer():
    def __init__(self,database,collation) -> None:
        self.client = pymongo.MongoClient('mongodb://ellis:ellischen@192.168.214.133:32000/')
        self.database = self.client[database]
        
        self.colleceion = self.database[collation]
        
    def insert_many(self,documents):
        self.colleceion.insert_many(documents)
        
    def lookup(self,destination,localField,foreignField,as_field):
        return self.colleceion.aggregate([{"$lookup":{"from":destination,"localField":localField,"foreignField":foreignField,"as":as_field}}])


server = MongoDBServer('lookup','orders')

for item in server.lookup("inventory","item","sku","inventory_docs"):
    print(item)
  1. lookup 与array类型一起使用
python 复制代码
import pymongo
import random
import string
from pymongo.collation import Collation

random.seed(10)
letters = string.ascii_lowercase
upper = string.ascii_uppercase


class MongoDBServer():
    def __init__(self,database,collation) -> None:
        self.client = pymongo.MongoClient('mongodb://ellis:ellischen@192.168.214.133:32000/')
        self.database = self.client[database]
        
        self.colleceion = self.database[collation]
        
    def insert_many(self,documents):
        self.colleceion.insert_many(documents)
        
    def lookup(self,destination,localField,foreignField,as_field):
        return self.colleceion.aggregate([{"$lookup":{"from":destination,"localField":localField,"foreignField":foreignField,"as":as_field}}])


server = MongoDBServer('lookup','classes')

server.insert_many([
   { "_id": 1, "title": "Reading is ...", "enrollmentlist": [ "giraffe2", "pandabear", "artie" ], "days": ["M", "W", "F"] },
   { "_id": 2, "title": "But Writing ...", "enrollmentlist": [ "giraffe1", "artie" ], "days": ["T", "F"] }
] )


server = MongoDBServer('lookup','members')

server.insert_many([
   { "_id": 1, "name": "artie",  "status": "A" },
   { "_id": 2, "name": "giraffe", "status": "D" },
   { "_id": 3, "name": "giraffe1",  "status": "A" },
   { "_id": 4, "name": "panda", "status": "A" },
   { "_id": 5, "name": "pandabear",  "status": "A" },
   { "_id": 6, "name": "giraffe2",  "status": "D" }
]  )
for item in server.lookup('members','enrollmentlist','name',"haha"):
    print(item)
  1. let以及pipeline的使用
python 复制代码
import pymongo
import random
import string
from pymongo.collation import Collation

random.seed(10)
letters = string.ascii_lowercase
upper = string.ascii_uppercase


class MongoDBServer():
    def __init__(self,database,collation) -> None:
        self.client = pymongo.MongoClient('mongodb://ellis:ellischen@192.168.214.133:32000/')
        self.database = self.client[database]
        
        self.colleceion = self.database[collation]
        
    def insert_many(self,documents):
        self.colleceion.insert_many(documents)
        
    def lookup(self,destination,localField,foreignField,as_field):
        return self.colleceion.aggregate([{"$lookup":{"from":destination,"localField":localField,"foreignField":foreignField,"as":as_field}}])


server = MongoDBServer('lookup','orders')


for item in server.colleceion.aggregate([
    {
        "$lookup":{
            "from": "inventory",
            "localField": "item",
            "foreignField": "sku",
            "let": {
                "instock": 100
            },
            "pipeline": [
                { "$match":
                    { "$expr":
                        { "$gt": [ "$instock", "$$instock"] }
                    }
                }
            ],
            "as": "haha"
        }
    },
    # {"$project":{"item":1,"price":1,"number":{"$size":"$haha"}}},
    # {"$match":{"number":{"$gte":1}}}
    {
        "$match":{"$expr":{"$gte":[{"$size":"$haha"}, 1]}}
    }
    
    
]):
    print(item)

https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/

相关推荐
white-persist21 分钟前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
Java 码农1 小时前
Centos7 maven 安装
java·python·centos·maven
安当加密1 小时前
MySQL数据库透明加密(TDE)解决方案:基于国密SM4的合规与性能优化实践
数据库·mysql·性能优化
倔强青铜三1 小时前
苦练Python第63天:零基础玩转TOML配置读写,tomllib模块实战
人工智能·python·面试
JH30732 小时前
第七篇:Buffer Pool 与 InnoDB 其他组件的协作
java·数据库·mysql·oracle
板凳坐着晒太阳2 小时前
ClickHouse 配置优化与问题解决
数据库·clickhouse
数据库生产实战2 小时前
解析Oracle 19C中并行INSERT SELECT的工作原理
数据库·oracle
浔川python社2 小时前
《网络爬虫技术规范与应用指南系列》(xc—3):合规实操与场景落地
python
B站计算机毕业设计之家2 小时前
智慧交通项目:Python+YOLOv8 实时交通标志系统 深度学习实战(TT100K+PySide6 源码+文档)✅
人工智能·python·深度学习·yolo·计算机视觉·智慧交通·交通标志
IT森林里的程序猿2 小时前
基于机器学习方法的网球比赛胜负趋势预测
python·机器学习·django