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

这篇博客介绍了MongoDB中$lookup操作与$mergeObjects的配合使用,强调了在关联时注意字段类型的匹配,如字符串与ObjectId。展示了如何指定多个连接条件,并给出了用例,包括数组关联、提升嵌入文档到顶层以及使用$expr进行复杂条件匹配。同时还提及了$replaceRoot、$arrayElemAt等操作的应用。
摘要由CSDN通过智能技术生成

使用$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 },
   {
    "_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": 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,
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正直的刘大炮.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值