首页 > 解决方案 > 在 mongo shell 中获取存储在 MongoDB 中的 BSON 类型的文档字段

问题描述

我的 MongoDB 数据库中有两个文档。它们是(简化的):

{
    "_id" : "ONE",
    "items": [
        42,
        0
    ]
}

{
    "_id" : "TWO",
    "items": [
        0,
        0
    ]
}

它们是由我怀疑的客户端应用程序(即不使用 MongoDB shell)创建的(我的意思是,应用程序可能有错误,我正在尝试调试它)。

我怀疑文档ONE中的数字在BSON 级别(即BSON 类型16)items编码为 32 位整数,而在文档中它们被编码为双精度(即BSON 类型1)TWO

我曾尝试typeof在 MongoDB shell 中使用 JavaScript 中的常用运算符对其进行检查,但似乎它们没有发现任何区别:

> typeof db.entities.find({_id: "ONE"})[0].items[0]
number
> typeof db.entities.find({_id: "ONE"})[0].items[1]
number
> typeof db.entities.find({_id: "TWO"})[0].items[0]
number
> typeof db.entities.find({_id: "TWO"})[0].items[1]
number

是否有任何精确的方法可以从 MongoDB shell 中了解给定 MongoDB 文档的 BSON 类型?

提前致谢!

标签: mongodbbsonmongo-shell

解决方案


你可以使用aggregate with $type

操场

而且您的理解并不完全正确。Mongo 默认将数字视为双倍。

请参阅下面的示例,我强制添加一个整数然后它说它是整数。它不打印类型编号而是类型名称

db.collection.aggregate([
  {
    "$unwind": "$items" //Denormalized
  },
  {
    "$addFields": {
      "x": {//All docs will have this - For demo purpose
        "$toInt": "11"
      }
    }
  },
  {
    "$project": {
      "t": {
        "$type": "$items" //Each element in the items - after denormalising
      },
      "t1": {
        "$type": "$x" //Type of newly added element
      }
    }
  }
])

推荐阅读