简体   繁体   中英

Get names of all keys name in collection using Java

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...
     */   
    }
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM