mongodb有$lookup可以做多表查询

举个例子

数据如下

db.orders.insert([
{ "_id" : , "item" : "almonds", "price" : , "quantity" : },
{ "_id" : , "item" : "pecans", "price" : , "quantity" : },
{ "_id" : }
])
db.inventory.insert([
{ "_id" : , "sku" : "almonds", description: "product 1", "instock" : },
{ "_id" : , "sku" : "bread", description: "product 2", "instock" : },
{ "_id" : , "sku" : "cashews", description: "product 3", "instock" : },
{ "_id" : , "sku" : "pecans", description: "product 4", "instock" : },
{ "_id" : , "sku": null, description: "Incomplete" },
{ "_id" : }
])

聚合操作如下

db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
},
])

上面的代码意思是,从order表中取item字段作为inventory表中sku的查询条件,然后把数据保存到inventory_docs字段,

等价于mysql中的

SELECT *, inventory_docs
FROM orders
WHERE inventory_docs IN (SELECT *
FROM inventory
WHERE sku= orders.item);

下面用pymongo实现

from pymongo import MongoClient

def test():
client = MongoClient()
db = client[db_name]
db['orders'].aggregate([{'$lookup':{'from': "inventory", "localField": "item", "foreignField": "sku", "as": "inventory_docs"}}])

这样就实现了上述的效果了

上述操作返回以下结果

{
"_id" : ,
"item" : "almonds",
"price" : ,
"quantity" : ,
"inventory_docs" : [
{ "_id" : , "sku" : "almonds", "description" : "product 1", "instock" : }
]
}
{
"_id" : ,
"item" : "pecans",
"price" : ,
"quantity" : ,
"inventory_docs" : [
{ "_id" : , "sku" : "pecans", "description" : "product 4", "instock" : }
]
}
{
"_id" : ,
"inventory_docs" : [
{ "_id" : , "sku" : null, "description" : "Incomplete" },
{ "_id" : }
]
}

看起来蛮方便的,但是其实很麻烦,如果我们只想显示inventory表中的某些字段,这样不符合我们的要求

这时候就需要用到$project和$arrayElemAt

如果我们只想显示inventory中的instock字段的话应该这样做

db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
},
{
$project:
{
'instock': {'$arrayElemAt':['$inventory_docs.instock', ]}
},
},
])

返回的结果是

{'_id': 1.0, 'instock': 120.0}
{'_id': 2.0, 'instock': 70.0}
{'_id': 3.0}

之前orders的数据好像没了,不用着急,在project里面添加想要返回的数据项即可

如我想要返回orders的price字段,在$project中添加{'price':1}即可,其他同

lookup更多详细用法

project可以指定返回的内容

 $project:
{
'sku':, 'item':,
}

指定返回sku和item

也可以重命名

$project:
{
'test': '$sku',
'item': ,
}

将sku字段重命名为test返回

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

mongodb多表查询(附带pymongo实例)的更多相关文章

  1. mongodb 多表查询

    今天有一个业务涉及到mongodb的多表查询,大体记录下语句结构 db.table_a.aggregate([ {$lookup:{from:"table_b",localFiel ...

  2. SAP内表查询速度优化实例-OPEN SQL

    一.FOR ALL ENTRIES IN 案例 今天碰到工单报工统计分析表查询速度特别慢 经查看源代码: SELECT afpo~dwerk afko~aufnr afpo~matnr AS plnb ...

  3. MongoDB联表查询

    表A: id name --------------------------- 1 Tom 2 Roger 3 Mars 4 Brent 表B: id result ----------------- ...

  4. NodeJs操作MongoDB之多表查询($lookup)与常见问题

    NodeJs操作MongoDB之多表查询($lookup)与常见问题 一,方法介绍 aggregate()方法来对数据进行聚合操作.aggregate()方法的语法如下 1 aggregate(ope ...

  5. Yii框架 多表查询实例

    Yii框架多表查询实例:总共分为两个步骤(以下的代码我全部都写在model中):1.先在主表model中声明关联表中所需要查询的字段. public $surveyls_description; // ...

  6. [重要] Django 多条件多表查询实例问题

    当时想做一个多条件查询,但是对于要查询的信息,是分布在不同的表里,这就涉及到了多表查询问题. DjangoBook里提到了一些查询的方式,但是不够全面,就去百度搜了下. 当去网上百度搜多表查询,或多条 ...

  7. Django 多条件多表查询实例问题

    当时想做一个多条件查询,但是对于要查询的信息,是分布在不同的表里,这就涉及到了多表查询问题. DjangoBook里提到了一些查询的方式,但是不够全面,就去百度搜了下. 当去网上百度搜多表查询,或多条 ...

  8. PHP.36-TP框架商城应用实例-后台12-商品管理-主分类添加、修改、搜索(连表查询)

    需求:一个商品必须有一个主分类,一个主分类可以有多个商品 [一对多] 修改表p39_goods,增加外键约束,增加索引 主分类添加[控制器->页面] 1.在控制器GoodsController. ...

  9. 010.简单查询、分组统计查询、多表连接查询(sql实例)

    -------------------------------------day3------------ --添加多行数据:------INSERT [INTO] 表名 [(列的列表)] --SEL ...

随机推荐

  1. 关于指针pointer的位数与程序有关还是与系统有关、以及指针的指针的理解

  2. ZOJ-3430

    Detect the Virus  Time Limit: 2 Seconds      Memory Limit: 65536 KB One day, Nobita found that his c ...

  3. Dubbo简单DEMO以及重要配置项

    DEMO pom.xml 消费方和服务提供方一致 <properties> <spring.version>4.0.6.RELEASE</spring.version&g ...

  4. js刷新页面代码

    第一种: location.reload() 第二种: location.replace(location.href) 第三种: history.go() 第四种: location=location ...

  5. python中global变量释疑

    疑问 为什么main中不能写global x语句? 在函数中如何修改global变量? 在main中修改了global变量后,在子进程中为什么没有效果? 如何利用进程池的initializer参数(函 ...

  6. 配置文件中的mime-mapping元素(ofbiz/framework/catalina/config/mime-type)(

    mime-mapping元素将mime类型映射到扩展名. extension元素用来描述扩展名.mime-type元素则为MIME类型. <?xml version="1.0" ...

  7. Jmeter-----随机生成手机号后8位并去重,来进行注册手机号的压测

    要求:对注册接口进行100000次压测,手机号已126开头,后面的8位数不限 前言:在进行测试中,我们需要对注册接口进行压测100000次,那么就要求手机号码每次填写的不一致,否则手机号使用一次后会出 ...

  8. Openstack 清除openstack网络与路由 (十七)

    一)清除openstack网络与路由 “清除openstack网络与路由”和”添加openstack网络与路由”的操作步骤相反. 添加网络或路由时是先建 搭建网络>搭建子网>建立端口, 而 ...

  9. Flask实战第38天:前台模型创建

    安装shortuuid pip install shortuuid 编辑front.models.py from exts import db import shortuuid from werkze ...

  10. nyoj 151 Biorhythms

    描述 Some people believe that there are three cycles in a person's life that start the day he or she i ...