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/