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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用$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
{
   
   
    "_i
### 使用 `Aggregation.$lookup` 实现多字段关联 为了实现基于多个字段的连接操作,在 MongoDB聚合框架中可以利用 `$lookup` 阶段来完成这一目标。当需要依据两个以上的字段来进行匹配时,可以通过构建复杂的查询条件并将其传递给 `$lookup` 来达成目的。 对于较新版本(如 3.6 及以上),支持通过定义更灵活的管道表达式作为外键文档的选择标准[^3]。这意味着可以在 `$lookup` 中嵌套一个完整的聚合管道,这使得能够根据源集合中的每一个输入文档动态地调整要从被引用集合获取的数据。 下面是一个具体的例子,展示如何使用带有自定义管道的 `$lookup` 进行跨集合间的多字段联合: 假设存在两个集合:`orders` 和 `customers`。现在希望找到所有订单及其对应的客户信息,并且这些客户的国家为中国(`country="China"`)并且城市为北京(`city="Beijing"`): ```javascript db.orders.aggregate([ { "$lookup": { "from": "customers", "let": { orderCountry: "$shippingAddress.country", orderCity: "$shippingAddress.city" }, "pipeline": [ { "$match": { "$expr": { "$and": [ {"$eq": ["$$orderCountry", "$address.country"]}, {"$eq": ["$$orderCity", "$address.city"]} ] } } }, { "$match": { "address.country": "China", "address.city": "Beijing" } } ], "as": "customerInfo" } } ]) ``` 此代码片段展示了如何设置变量 (`let`) 并在后续的 `$match` 子句里应用它们以确保只有满足特定条件的记录才会被加入到最终的结果集中[^1]。 此外,如果只是简单计数而不关心具体数据,则可考虑采用简化形式即 `$count` 舞台代替冗长的手动分组加投影组合[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

正直的刘大炮.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值