如何从Java中的mongodb中的BasicDBList创建List <string>?</string>

时间:2014-05-10 08:04:20

标签: java json mongodb

存储在mongodb数据库中的JSON格式为

{
        "genre":  ["Action", "Animation", "Drama"],
        "movie_id": 1
}

我必须得到一个类型列表。对不起,如果问题很蹩脚。我是Java和mongodb的新手。

3 个答案:

答案 0 :(得分:10)

我建议使用以下代码来解决您的问题:

MongoClient mongo = new MongoClient( "localhost" , 27017 );
DB db = mongo.getDB(dbName);
DBCollection collection = db.getCollection(collectionName);

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("movie_id", id);

DBObject document = collection.findOne(whereQuery);
BasicDBList list = (BasicDBList) document.get("genre");

List<String> res = new ArrayList<String>();

for(Object el: list) {
     res.add((String) el);
}

答案 1 :(得分:0)

查找

{
    "genre":  ["Action", "Animation", "Drama"],
    "movie_id": 1,
    "attributes" : [ 
        {
            "name" : "name 1",
            "value" : "value 1"
        }, {
            "name" : "name 2",
            "value" : "value 2"
        }
    ]
}

您可以使用:

DBObject dbObject = (DBObject) object.get("attributes");
BasicDBList list = new BasicDBList();
for (String key : dbObject.keySet()) {
    list.add(dbObject.get(key));
}

List<String> listArray = new ArrayList<String>();
for (Object object : list) {
    listArray.add(object.toString());
}

DBObject dbObject = (DBObject) object.get("genre");
List<String> listArray = new ArrayList<String>();
for (String key : dbObject.keySet()) {
    list.add(((DBObject) dbObject.get(key)).toString());
}

你也可以(但是,可能不工作)

BasicDBList list = (BasicDBList) object.get("attributes");
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
    listArray.add(((DBObject) object).toString());
}

BasicDBList list = (BasicDBList) object.get("genre");
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
    listArray.add(object.toString());
}

答案 2 :(得分:-2)

    DBObject channelDBObject = new BasicDBObject(); 
    System.out.println("genre");
    String genre = bufferReader.readLine();
    String[] temp = genre.split(","); 
    int i=0; 
    BasicDBList genreDBList = new BasicDBList(); 
    DBObject genreDBObject = null; 
    while(i<temp.length){ 
        genreDBObject = new BasicDBObject(); 
        genreDBObject.put("genre",temp[i++]);
        genreDBList.add(genreDBObject); 
    } 
    channelDBObject.put("genre",genreDBList.toArray());
    System.out.println("Movie Id");
    String MovieId = bufferReader.readLine();
    channelDBObject.put("MovieId",Integer.parseInt(MovieId));
    dBCollection.insert(channelDBObject); 
    DBCursor dbcursor = dBCollection.find(); 
    while (dbcursor.hasNext())System.out.println(dbcursor.next()); 
}