• MongoDB关联查询


    Aggregate

    1. 在 MongoDB 中属于重量级工具
    2. pipeline 管道模型理论:后面操作的数据源来源于上一次操作的结果
    3. pipeline aggregate stages
    $project // 指定获取字段
    $match // 筛选
    $redact
    $limit
    $skip
    $unwind
    $group
    $sample
    $sort
    $geoNear
    $lookup // 关联
    $out
    $indexStats
    

    $lookup 关联表

    product 表:

    _id productname price
    1.0 商品1 15.0
    2.0 商品2 36.0

    orders 表:

    _id pid ordername
    1.0 1.0 订单1
    2.0 2.0 订单2
    3.0 3.0 订单3
    4.0 4.0 订单4
    db.product.aggregate([
         {
           $lookup:
             {
                from: "orders", // 需要关联的表
                localField: "_id", // product 表需要关联的键
                foreignField: "pid", // orders 的 matching key
                as: "inventory_docs" // 对应的外键集合的数据
              }
        }
     ])
    

    $match 筛选数据

    // 筛选出价格 大于 20 的商品
    db.product.aggregate([
        {
           $lookup: {
                from: "orders", // 需要关联的表
                localField: "_id", // product 表需要关联的键
                foreignField: "pid", // orders 的 matching key
                as: "inventory_docs" // 对应的外键集合的数据
            }
        },
        {
            $match: {
               price: { $gt:20 }
            }
        }
     ])
    

    $project 指定获取字段

    // 价格大于 20 的订单
    db.product.aggregate([
        {
           $lookup: {
                from: "orders", // 需要关联的表
                localField: "_id", // product 表需要关联的键
                foreignField: "pid", // orders 的 matching key
                as: "inventory_docs" // 对应的外键集合的数据
            }
        },
        {
            $match: {
               price: { $gt:20 }
            }
        },
        {
            $project:{
                "inventory_docs": 1,
                "_id": 0
            }
        }
     ])
    
    内容来源于网络或书籍
  • 相关阅读:
    VMware下ubuntu与win8共享文件时/mnt/hgfs目录为空的解决办法
    Flex Array内置排序方法的使用
    Flex 选项卡加载方式简介
    Flash Builder 4.6 基本设置
    Flash Builder 4.6 找不到所需的Adobe Flash Player
    2 python--工具pycharm
    1 python--安装
    安装aix补丁包
    python_day02 上节课知识点回顾
    vue组件局部与全局注册的区别
  • 原文地址:https://www.cnblogs.com/my3306/p/9712494.html
Copyright © 2020-2023  润新知