如何查找 Mongo 中所有字段的数据类型

How to find datatype of all the fields in Mongo

我有一个文档

{_id:NumberLong(1),gender:"M",vip:false}.

如何使用查询提取 Mongo 中单个字段的类型.. 如何使用typeof运算符:

https://docs.mongodb.org/manual/core/shell-types/

例如,您可以查询 gender 字段的类型:

typeof db.getCollection('your_collection').findOne({"_id": NumberLong(1)}).gender
> db.test.findOne()
{ "_id" : NumberLong(1), "gender" : "M", "vip" : false }
> db.test.findOne().gender
M
> typeof db.test.findOne().gender
string

问题标题询问所有字段,答案告诉如何用一个字段完成。这是一个所有文档字段的方法(只需更改开头的 your_collection 部分):

[db.your_collection.findOne()].forEach( function(my_doc) { for (var key in my_doc) { print(key + ': ' + typeof my_doc[key]) } } )

首先从 collection 中获取文档,然后使用 [] 将其转换为数组,以便我们可以使用 forEach 应用函数,最后在函数中迭代文档字段以打印它们键和我们想要的类型。这应该输出如下内容:

_id: object
gender: string
vip: boolean