mongodb - 在 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 类型?
提前致谢!
解决方案
你可以使用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
}
}
}
])
推荐阅读
- rest - REST 微服务 api 读取后如何将属性文件保存在某个本地内存中
- android - 如何从地图轨迹创建视频
- json - laravel 5.7 中的嵌套 json 响应
- php - 与日期相关的 PHP 错误
- python - 如何在 Nameko 的依赖提供程序中使用 Config?
- python - 如何同时配置 django server 和 react server 到 AWS elastic beanstalk 服务
- java - 如何根据字符串数组中出现的单词对地图进行排序
- java - 即使设置了 serialVersionUID,反序列化也会引发 InvalidClassException
- python - 朴素贝叶斯分类器和训练数据
- javascript - Javascript | 拼接从数组中删除错误的项目