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

如何查询同一集合中不同二进制子类型的两种格式GUID/_id?

MongoDB中查询不同格式的GUID类型_id

你的集合里存在两种格式的_id:一种是字符串形式的UUID(如'4e519e66-751c-4ef3-9a06-3de70b95b755'),另一种是子类型为3的BinData(即Legacy UUID,如BinData(3, 'Zp5RThx1806aBj3nC5W3VQ=='))。以下是针对这两种类型的查询方法:

查询字符串类型的UUID格式_id

直接通过$type匹配字符串类型的_id:

db.collection.find({ _id: { $type: "string" } })

如果需要精准匹配UUID的标准格式(避免匹配其他无关字符串),可以使用正则表达式:

db.collection.find({ _id: { $regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i } })

查询子类型为3的BinData格式_id

通过$type指定二进制子类型3(对应Legacy UUID):

db.collection.find({ _id: { $type: 3 } })

MongoDB 4.4及以上版本,也可以用$binarySubType直接指定子类型:

db.collection.find({ _id: { $binarySubType: 3 } })

同时查询两种格式的文档

使用$or操作符组合两个查询条件:

db.collection.find({
  $or: [
    { _id: { $type: "string" } },
    { _id: { $type: 3 } }
  ]
})

额外:格式转换(可选)

如果需要在两种格式间转换,可以用聚合操作:

  • 字符串UUID转BinData(3):
db.collection.aggregate([
  { $match: { _id: { $type: "string" } } },
  {
    $addFields: {
      convertedId: {
        $toBinData: { input: "$_id", format: "uuidLegacy" }
      }
    }
  }
])
  • BinData(3)转字符串UUID:
db.collection.aggregate([
  { $match: { _id: { $type: 3 } } },
  {
    $addFields: {
      convertedId: {
        $toString: "$_id"
      }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:10:16