返回MongoDB中字段的实际类型 [英] Return actual type of a field in MongoDB

查看:307
本文介绍了返回MongoDB中字段的实际类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中,使用$type可以根据字段是否匹配BSON数据类型来过滤搜索(请参见

In MongoDB, using $type, it is possible to filter a search based on if the field matches a BSON data type (see DOCS).

例如.

db.posts.find({date2: {$type: 9}}, {date2: 1})

返回:

{ 
    "_id" : ObjectId("4c0ec11e8fd2e65c0b010000"), 
    "date2" : "Fri Jul 09 2010 08:25:26 GMT" 
}

对于集合中的每个字段,我需要一个查询来告诉我该字段的实际类型是什么. MongoDB有可能吗?

I need a query that will tell me what the actual type of the field is, for every field in a collection. Is this possible with MongoDB?

推荐答案

好的,以下是一些相关的问题,可能会有所帮助:

OK, here are some related questions that may help:

使用map-reduce在集合中获取所有字段名称.

这是一个递归版本,其中列出了所有可能的字段.

Here's a recursive version that lists all possible fields.

希望这可以帮助您入门.但是,我怀疑您会在此请求上遇到一些问题.这里有两个问题:

Hopefully that can get you started. However, I suspect that you're going to run into some issues with this request. There are two problems here:

  1. 我找不到JSON的"gettype"函数.您可以通过$type进行查询,但是看起来您实际上不能在字段上运行gettype函数并使它映射回BSON类型.
  2. 一个字段可以包含多种类型的数据,因此您需要一个计划来处理它.即使不是很明显,Mongo也会在您不真正知道的情况下将一些数字存储为整数,而另一些则是浮点数.实际上,使用PHP驱动程序,这是完全有可能的.
  1. I can't find a "gettype" function for JSON. You can query by $type, but it doesn't look like you can actually run a gettype function on a field and have that maps back to the BSON type.
  2. A field can contain data of multiple types, so you'll need a plan to handle this. Even if it's not apparent Mongo could store some numbers as ints and others floats without you really knowing. In fact, with the PHP driver, this is quite possible.

因此,如果您假设可以解决问题#1,则应该可以对获取所有字段名称" 进行细微改动来解决问题#2.

So if you assume that you can solve problem #1, then you should be able to solve problem #2 using a slight variation on "Get all field Names".

它可能看起来像这样:

"map" : function() { for (var key in this) { emit(key, [ typeof value[key] ]); } }
"reduce" : function(key, stuff) { return (key, add_to_set(stuff) ); }

因此,基本上,您将在map函数中发出keytype of key value(作为数组).然后,通过reduce函数,您可以为每种类型添加唯一的条目.

So basically you would emit the key and the type of key value (as an array) in the map function. Then from the reduce function you would add unique entries for each type.

运行结束时,您将获得类似这样的数据

At the end of the run you would have data like this

{"_id":[255], "name" : [1,5,8], ... }

当然,这是很多工作,根据您的实际问题,您可能只想确保(通过代码)始终输入正确的数据类型.在将数据放入数据库之后,查找数据的类型肯定很麻烦.

Of course, this is all a lot of work, depending on your actual problem, you may just want to ensure (from your code) that you're always putting in the right type of data. Finding the type of data after the data is in the DB is definitely a pain.

这篇关于返回MongoDB中字段的实际类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆