0

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 :(

Let's say I have I have the flowing BSON documents:

{
_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?

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.

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());
SQL.injection
  • 2,607
  • 5
  • 20
  • 37

1 Answers1

1

A DBObject has a method called keySet (documentation). You shouldn't need to convert to a Map first.

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.

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.

WiredPrairie
  • 58,954
  • 17
  • 116
  • 143