Reputation: 345
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.
Upvotes: 6
Views: 17245
Reputation: 1419
Look:
{
"genre": ["Action", "Animation", "Drama"],
"movie_id": 1,
"attributes" : [
{
"name" : "name 1",
"value" : "value 1"
}, {
"name" : "name 2",
"value" : "value 2"
}
]
}
You can use:
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());
}
and
DBObject dbObject = (DBObject) object.get("genre");
List<String> listArray = new ArrayList<String>();
for (String key : dbObject.keySet()) {
list.add(((DBObject) dbObject.get(key)).toString());
}
You can too (but, maybe don't working):
BasicDBList list = (BasicDBList) object.get("attributes");
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
listArray.add(((DBObject) object).toString());
}
and
BasicDBList list = (BasicDBList) object.get("genre");
List<String> listArray = new ArrayList<String>();
for (Object object : list) {
listArray.add(object.toString());
}
Upvotes: 0
Reputation: 1
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());
}
Upvotes: -3
Reputation: 626
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);
}
Upvotes: 12