db.dimensions.insert({
"GeoLevels": [{
"5": "Continent_Name"
}, {
"4": "Country_Name"
}, {
"3": "Region_Name"
}, {
"2": "State_Name"
}, {
"1": "City_Name"
}],
"AssetLevels": [{
"2": "Asset_Model"
}, {
"1": "Asset_Class"
}],
"TimeLevels": [{
"4": "Year"
}, {
"3": "Qtr"
}, {
"2": "Month"
}, {
"1": "Week"
}]
})
如何使用mongodb和java
读取上述每个值答案 0 :(得分:0)
您应该能够将DBObject转换为其中一个实现(请参阅此处的所有实现:http://api.mongodb.org/java/current/com/mongodb/DBObject.html),在本例中为BasicDBList,它扩展了ArrayList,因此您可以使用arrayList中的所有方法。
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("test");// Use DB
DBObject allQuery = new BasicDBObject();
DBCollection collection = db.getCollection("dimensions");
DBCursor curs = collection.find();
Iterator<DBObject> fields = curs.iterator();
while(fields.hasNext()){ //
BasicDBList geoList = (BasicDBList) fields.next().get("GeoLevels");
BasicDBObject object = (BasicDBObject) geoList.get(0); // this should return {"5": "Continent_Name"}
Object value = object.get("5); // value should contain "Continent_Name"
}
我还建议您查看Spring-data mongodb,它允许您将MongoDB中的对象直接映射到POJO,这样就可以更轻松地使用它了: