[英]How to retrieve the schema of a DBObject?
In mySQL the describe
statement can be used to retrieve the schema of a given table, unfortunately I could not locate a similar functionality for the MongoDB java driver :( 在mySQL中, describe
语句可用于检索给定表的架构,不幸的是,我无法为MongoDB Java驱动程序找到类似的功能:(
Let's say I have I have the flowing BSON documents: 假设我有流动的BSON文档:
{
_id: {$oid:49},
values: { a:10, b:20}
}
,
{
_id: {$oid:50},
values: { b:21, c:31}
}
Now let's suppose I do: 现在假设我这样做:
DBObject obj = cursor.next();
DBObject values_1 = (DBObject) obj.get("values");
and the schema should be something like this: 架构应该是这样的:
>a : int
>b : int
and for the next document: 对于下一个文档:
DBObject obj = cursor.next();
DBObject values_2 = (DBObject) obj.get("values");
the schema should be: 模式应为:
>b : int
>c : int
Now that I explained what the schema retrial is, can some1 be nice and tell me how to do it? 现在,我解释了模式重试是什么,some1可以很好地告诉我如何做吗?
If it helps, In ma case I only need to know the field names (because the datatype is always the same, but it would be nice also know how to retrieve the datatypes). 如果有帮助,在某些情况下,我只需要知道字段名称(因为数据类型总是相同的,但是也很高兴知道如何检索数据类型)。
A work arround, is convert the DBObject to a Map, then the Map to a Set, the Set to an Iterator and extract the attribute names/values... Still have now idea how to extract data types. 一项工作是将DBObject转换为Map,然后将Map转换为Set,将Set转换为Iterator并提取属性名称/值...现在仍然知道如何提取数据类型。
this is: 这是:
DBObject values_1 = (DBObject) obj.get("values");
Map _map = values_1.toMap();
// Set set = _map.entrySet(); // if you want the <key, value> pairs
Set _set_keys = _map.keySet();
Iterator _iterator = _set_keys.iterator();
while (_iterator.hasNext())
System.out.println("-> " + _iterator.next());
A DBObject
has a method called keySet
( documentation) . DBObject
具有称为keySet
( 文档)的方法 。 You shouldn't need to convert to a Map
first. 您不需要先转换为Map
。
There's no exposed method to determine the underlying BSON data type at this point, so you'd need to investigate using instanceof
or getClass
to determine the underlying data type of the Object
that is returned from get
. 目前尚无公开的方法来确定基础BSON数据类型,因此您需要研究使用instanceof
或getClass
来确定从get
返回的Object
的基础数据类型。
If you look at the source code for BasicBSONObject
for example, you'll see how the helper functions that cast do some basic checks and then force the cast. 例如,如果您查看BasicBSONObject
的源代码,您将看到进行BasicBSONObject
的辅助函数如何进行一些基本检查,然后强制进行强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.