Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a List<String> from a BasicDBList in mongodb in Java?

Tags:

java

json

mongodb

The JSON stored in mongodb database is of form

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

I have to get a list of genres. Sorry if the question is lame. I'm kinda new to Java and mongodb.

like image 301
khirod Avatar asked May 10 '14 08:05

khirod


1 Answers

i propose the below code to solve your issue:

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);
}
like image 119
jmen7070 Avatar answered Nov 15 '22 00:11

jmen7070