javascript - 在js脚本中获取mongodb数据类型

标签 javascript shell mongodb

db.foo.find();


_id    | type
-------------
10001     1
10002    'a'
10003    [1, 2, 3, 4]

如您所知,$type 将匹配 mongo 查询中的类型代码,如下所示:

db.foo.find({type: {$type: 4}});

_id |类型

----------

10003,[1,2,3,4]

然后,我编写了一个名为 test.js

的 javascript shell 脚本
var curs = db.foo.find();
curs.forEach(showTypeCode);
function showTypeCode(cur) {
  print(cur.type + '-' + typeof(cur.type));
};

结果:

1-number
a-string
1,2,3,4-object (this is an array, it's 4 in mongo)

这是我的问题,如何在 mongo shell 中获取数组类型代码

最佳答案

您的第一个查询:

db.foo.find({type: {$type: 4}});

由于错误,实际上无法工作。这是 MongoDB 中的一个已知错误,它在使用 $type 运算符时将数组读取为对象。您可以投票并支持此 JIRA:https://jira.mongodb.org/browse/SERVER-1475

关于用JS解决问题,这个问题可能对你有帮助:Detect if parameter passed is an array? Javascript

数组是数组类的对象,因此这就是您获取对象的原因。如果您测试 Array 的实例,那么它应该可以工作。

关于javascript - 在js脚本中获取mongodb数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13340546/

相关文章:

javascript - 没有PHP的表单提交

bash - 如何缩小/混淆 bash 脚本

mongodb - 如何将mongo.InsertOneResult的InsertedID转换为[] byte

Linux - 使用 CLI 程序执行命令

php - 对于大型数据库来说,哪种 dB 语言既快速又稳定?

node.js - 在node.js/mongoDB中更新时发送后无法设置 header

Javascript 对多语言的排序支持

javascript - Angular:无法识别来自共享模块的组件

javascript - React Native 中对象的顺序对象

linux - 需要使用 unix 脚本移动具有文件路径的目录中的文件名