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

MongoDB跨集合查询:匹配sourcemmsi前三位的记录

MongoDB跨集合关联查询实现方案

要实现基于sourcemmsi前三位关联Ship_Data和SourceMMSI集合的查询,可以用MongoDB的聚合管道配合$lookup操作完成,核心是先提取sourcemmsi的前三位前缀,再与SourceMMSI的mmsi_code匹配,具体有两种实现思路:


方法一:数值运算提取前缀(推荐,适用于sourcemmsi为数值类型)

因为sourcemmsi是9位数字,直接通过数值除法取整即可得到前三位:

db.Ship_Data.aggregate([
  // 生成前三位的mmsi前缀字段
  {
    $addFields: {
      mmsi_prefix: { $floor: { $divide: ["$sourcemmsi", 1000000] } }
    }
  },
  // 关联SourceMMSI集合
  {
    $lookup: {
      from: "SourceMMSI",
      localField: "mmsi_prefix",
      foreignField: "mmsi_code",
      as: "country_info"
    }
  },
  // 展开关联结果数组(保留未匹配到国家的船舶记录)
  {
    $unwind: {
      path: "$country_info",
      preserveNullAndEmptyArrays: true
    }
  },
  // 整理输出字段(移除临时前缀和不需要的_id)
  {
    $project: {
      mmsi_prefix: 0,
      "country_info._id": 0
    }
  }
])

方法二:字符串转换提取前缀(适用于可能存在前导零的场景)

先将sourcemmsi转为字符串,截取前三位后再转回数值匹配:

db.Ship_Data.aggregate([
  {
    $addFields: {
      mmsi_prefix: {
        $toInt: { $substrCP: [{ $toString: "$sourcemmsi" }, 0, 3] }
      }
    }
  },
  {
    $lookup: {
      from: "SourceMMSI",
      localField: "mmsi_prefix",
      foreignField: "mmsi_code",
      as: "country_info"
    }
  },
  {
    $unwind: {
      path: "$country_info",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      mmsi_prefix: 0,
      "country_info._id": 0
    }
  }
])

查询结果示例

执行后每条船舶记录会附带匹配到的国家信息:

{
  _id: ObjectId("63d19d7a1991a09011aa35ef"),
  sourcemmsi: 228051000,
  navigationalstatus: 0,
  course: {
    rateofturn: -127,
    speedoverground: 0,
    courseoverground: 291.5,
    trueheading: 511
  },
  coordinates: {
    longitude: -4.4850965,
    latitude: 48.38132,
    timestamp: 1443650424
  },
  country_info: {
    mmsi_code: 228,
    country: 'France'
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:46:28