在此集合中(称为“播放”)
{ "_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"}
如何使用Java检索密钥的名称?
示例输出:
[ "_id" , "outlook" , "temp" , "humidity" , "windy" , "lable" ]
到目前为止,代码看起来像这样
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...
*/
}
}
答案 0 :(得分:2)
如果您在DBCursor.next()
处查看API,则会返回DBObject
,这是BSONObject
with a keySet()
方法的子类型。该字段为Set<String>
,其描述为
此对象中字段的名称
因此,您可以使用
for (String key: cursor.next().keySet()) {
// do whatever with the key name here, f.ex.
System.out.println(key);
}