mongodb有$lookup可以做多表查询

举个例子

数据如下

  1. db.orders.insert([
  2. { "_id" : , "item" : "almonds", "price" : , "quantity" : },
  3. { "_id" : , "item" : "pecans", "price" : , "quantity" : },
  4. { "_id" : }
  5. ])
  6. db.inventory.insert([
  7. { "_id" : , "sku" : "almonds", description: "product 1", "instock" : },
  8. { "_id" : , "sku" : "bread", description: "product 2", "instock" : },
  9. { "_id" : , "sku" : "cashews", description: "product 3", "instock" : },
  10. { "_id" : , "sku" : "pecans", description: "product 4", "instock" : },
  11. { "_id" : , "sku": null, description: "Incomplete" },
  12. { "_id" : }
  13. ])

聚合操作如下

  1. db.orders.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "inventory",
  6. localField: "item",
  7. foreignField: "sku",
  8. as: "inventory_docs"
  9. }
  10. },
  11. ])

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

等价于mysql中的

  1. SELECT *, inventory_docs
  2. FROM orders
  3. WHERE inventory_docs IN (SELECT *
  4. FROM inventory
  5. WHERE sku= orders.item);

下面用pymongo实现

  1. from pymongo import MongoClient
  2.  
  3. def test():
  4. client = MongoClient()
  5. db = client[db_name]
  6. db['orders'].aggregate([{'$lookup':{'from': "inventory", "localField": "item", "foreignField": "sku", "as": "inventory_docs"}}])

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

上述操作返回以下结果

  1. {
  2. "_id" : ,
  3. "item" : "almonds",
  4. "price" : ,
  5. "quantity" : ,
  6. "inventory_docs" : [
  7. { "_id" : , "sku" : "almonds", "description" : "product 1", "instock" : }
  8. ]
  9. }
  10. {
  11. "_id" : ,
  12. "item" : "pecans",
  13. "price" : ,
  14. "quantity" : ,
  15. "inventory_docs" : [
  16. { "_id" : , "sku" : "pecans", "description" : "product 4", "instock" : }
  17. ]
  18. }
  19. {
  20. "_id" : ,
  21. "inventory_docs" : [
  22. { "_id" : , "sku" : null, "description" : "Incomplete" },
  23. { "_id" : }
  24. ]
  25. }

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

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

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

  1. db.orders.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "inventory",
  6. localField: "item",
  7. foreignField: "sku",
  8. as: "inventory_docs"
  9. }
  10. },
  11. {
  12. $project:
  13. {
  14. 'instock': {'$arrayElemAt':['$inventory_docs.instock', ]}
  15. },
  16. },
  17. ])

返回的结果是

  1. {'_id': 1.0, 'instock': 120.0}
  2. {'_id': 2.0, 'instock': 70.0}
  3. {'_id': 3.0}

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

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

lookup更多详细用法

project可以指定返回的内容

  1. $project:
  2. {
  3. 'sku':, 'item':,
  4. }

指定返回sku和item

也可以重命名

  1. $project:
  2. {
  3. 'test': '$sku',
  4. 'item': ,
  5. }

将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. 《逐梦旅程 WINDOWS游戏编程之从零开始》笔记3——输入消息处理,物理建模与粒子系统初步

    第7章 Windows游戏输入消息处理 1. 键盘消息处理 之前提到的窗口过程函数有两参数与消息输出有关——wParam和llParam LRESULT CALLBACK WindowProc( _I ...

  2. python调用.so

    python调用动态链接库的基本过程 动态链接库在Windows中为.dll文件,在linux中为.so文件.以linux平台为例说明python调用.so文件的使用方法. 本例中默认读者已经掌握动态 ...

  3. css 三(清除浮动专题)

    1.  三个关于浮动的概念  不浮动float:none; 清除周围的浮动元素   float:both   这是清除浮动的本意 清除子元素浮动对父元素的影响  clearfix    很多人都理解成 ...

  4. destoon 部署到服务器如何修改密码使网站能正常访问登录

    1.根目录的config.inc.php  修改 db_pass 2.缓存文件 根目录/file/cache/module-2.php   修改 uc_dbpwd PS:不一定都在module-2.p ...

  5. WeGame导致WSL无法监听端口问题

    Windows 10 系统自带Linux子系统(WSL),可以方便的使用WSL运行Linux程序和脚本.笔者在WSL上运行Redis时突然发现无法监听6379端口,尝试重新安装WSL无果. 后来重新安 ...

  6. 使用Spring JdbcTemplate实现CLOB和BLOB的存取

    概述 本文讲述通过Spring的JdbcTemplate来读写数据库大字段的实现方案,在一位网友的一篇博客的基础上,查看api文档整理而成. 写实现 JdbcTemplate jdbcTemplate ...

  7. webpack 打包过程及常用插件

    前言 要理解webpack 首先明白三个概念:module,chunk,bundles,即输入,中间态,输出. chunk: This webpack-specific term is uesd in ...

  8. linux的bash和shell关系

    shell通俗理解:把用户输入的命令翻译给操作系统. shell 是一个交互性命令解释器.shell独立于操作系统,这种设计让用户可以灵活选择适合自己的shell.shell让你在命令行键入命令,经过 ...

  9. 【BZOJ 3881】【COCI 2015】Divljak

    http://www.lydsy.com/JudgeOnline/problem.php?id=3881 好难的一道题啊qwq 一开始我想对T建AC自动机,根本不可做. 正解是对S建AC自动机. fa ...

  10. 【数据结构】Not so Mobile (6-9)

    [UVA839]Not so Mobile 算法入门经典第6章6-9(P157) 题目大意:输入一个树状天平,根据力矩相等原则判断是否平衡. 试题分析:貌似没有什么难点…… #include<i ...