MongoDB聚合管道 $lookup 与$mergeObjects配合使用 以及使用let,pipeline自定义参数进行指定多个连接条件

使用$lookup$mergeObjects配合使用以及进行指定多个连接条件

注意!!

$lookup是如果涉及关联"_id",注意两个字段的类型,用string类型匹配ObjectId类型是关联不上的

准备数据

//订单表
db.orders.insert([
   {
    "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
   {
    "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
   {
    "_id" : 3  }
])
//库存表
db.inventory.insert([
   {
    "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 }, "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": null, description: "Incomplete" },
   {
    "_id" : 6 }
])

两种用法
1.一种关联

{
   
   $lookup:
     {
   
       //要关联的从表名
       from: <collection to join>,
       //主表关联字段
       localField: <field from the input documents>,
       //从表中与主表关联的字段
       foreignField: <field from the documents of the "from" collection>, 
       //别名
       as: <output array field>	
     }
}

2.自定义多种关联

{
   
   $lookup:
     {
   
       //要关联的从表名
       from: <collection to join>,
       //自定义变量有一个或多个变量
       let: {
    <var_1>: <expression>,, <var_n>: <expression> },
       //自定义的操作从表的聚合但不允许使用out和merge操作
       pipeline: [ <pipeline to execute on the collection to join> ],
       //别名
       as: <output array field>	
     }
}

orders表为主表 inventory表为从表 根据 orders表的item字段与inventory表的sku进行关联

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

该操作返回以下文档:

// 1
{
   
    "_id": 1,
    "item": "almonds",
    "price": 12,
    "quantity": 2,
    "inventory_docs": [
        {
   
            "_id": 1,
            "sku": "almonds",
            "description": "product 1",
            "instock": 120
        }
    ]
}

// 2
{
   
    "_id": 2,
    "item": "pecans",
    "price": 20,
    "quantity": 1,
    "inventory_docs": [
        {
   
            "_id": 4,
            "sku": "pecans",
            "description": "product 4",
            "instock": 70
        }
    ]
}

// 3
{
   
    "_id": 3,

相关文章

文章浏览阅读752次。关系型数据库关系型数据库是一个结构化的...
文章浏览阅读687次,点赞2次,收藏5次。商城系统中,抢购和秒...
文章浏览阅读1.4k次。MongoTemplate开发spring-data-mongodb...
文章浏览阅读887次,点赞10次,收藏19次。1.背景介绍1. 背景...
文章浏览阅读819次。MongoDB连接失败记录_edentialmechanisn...
文章浏览阅读470次。mongodb抽取数据到ES,使用ELK内部插件无...