You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用MongoDB聚合管道识别无对应描述的订单?

基于联合主键查找MongoDB中无匹配的订单记录

实现代码

db.orders.aggregate([
  // 关联productInfo集合,通过orderID和productCode联合匹配
  {
    $lookup: {
      from: "productInfo",
      let: {
        current_order_id: "$orderID",
        current_product_code: "$productCode"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                { $eq: ["$orderID", "$$current_order_id"] },
                { $eq: ["$productCode", "$$current_product_code"] }
              ]
            }
          }
        }
      ],
      as: "matched_records"
    }
  },
  // 筛选出无匹配结果的订单
  {
    $match: {
      matched_records: { $size: 0 }
    }
  },
  // 仅返回需要的字段
  {
    $project: {
      _id: 0,
      orderID: 1,
      productCode: 1
    }
  }
])

代码说明

  1. $lookup阶段:
    • from指定关联的目标集合productInfo
    • let定义局部变量,存储当前orders文档的orderID和productCode值
    • 内部pipeline使用$match结合$expr,通过变量实现联合字段匹配,只有当两个字段完全对应时才会返回匹配结果
    • as将匹配结果存入matched_records数组,无匹配时该数组为空
  2. $match阶段:过滤出matched_records数组长度为0的文档,也就是在productInfo中没有对应联合主键的订单
  3. $project阶段:仅保留orderID和productCode字段,剔除默认的_id

示例数据执行结果

针对你提供的示例数据,运行上述代码后会返回以下结果:

[
  { "orderID" : 10340, "productCode" : 1 },
  { "orderID" : 10341, "productCode" : 2 },
  { "orderID" : 10342, "productCode" : 3 },
  { "orderID" : 10343, "productCode" : 4 }
]

(注:示例中productInfo仅包含(10340,2)和(10342,4)两组联合键,因此orders中其余记录均被筛选出来)

内容的提问来源于stack exchange,提问作者BreenDeen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:35:25