Reputation: 397
In this collection (called "play")
{ "_id" : 0 , "outlook" : "sunny" , "temp" : "hot" , "humidity" : "high" , "windy" : "weak" , "lable" : "no"}
{ "_id" : 1 , "outlook" : "sunny" , "temp" : "hot" , "humidity" : "high" , "windy" : "strong" , "lable" : "no"}
{ "_id" : 2 , "outlook" : "overcast" , "temp" : "hot" , "humidity" : "high" , "windy" : "weak" , "lable" : "yes"}
{ "_id" : 3 , "outlook" : "rain" , "temp" : "mild" , "humidity" : "high" , "windy" : "weak" , "lable" : "yes"}
{ "_id" : 4 , "outlook" : "rain" , "temp" : "cool" , "humidity" : "normal" , "windy" : "weak" , "lable" : "yes"}
{ "_id" : 5 , "outlook" : "rain" , "temp" : "cool" , "humidity" : "normal" , "windy" : "strong" , "lable" : "no"}
How can I retrieve the names of the keys using Java?
Example output:
[ "_id" , "outlook" , "temp" , "humidity" , "windy" , "lable" ]
The code looks like this so far
public class test {
public static void main(String[] args) {
DB dbtest = connection.dbconn();
DBCollection collection = dbtest.getCollection("play");
BasicDBObject allQuery = new BasicDBObject();;
DBCursor cursor = collection.find(allQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
/**
write code.. here...
*/
}
}
Upvotes: 0
Views: 2127
Reputation: 38147
If you look in the API at DBCursor.next()
, it returns a DBObject
, which is a subtype of BSONObject
with a keySet()
method. That field is a Set<String>
, with the description
The names of the fields in this object
Thus, you might be able to use
for (String key: cursor.next().keySet()) {
// do whatever with the key name here, f.ex.
System.out.println(key);
}
Upvotes: 3