2

I want to fetch array elements from mongoDB and display it, here is my sample code.

String[] previliges = new String[20];
String g_name = (String)jComboBox2.getSelectedItem();
DBCursor f;
BasicDBObject query = new BasicDBObject("group_name", g_name);

connection.MongoConnection con = new MongoConnection();
con.createConnection();
con.selectDB("test", "user_group");

f = con.coll.find(query);
previliges = (String[])f.next().get("privileges");
System.out.println(previliges.length);

it is giving me an exception that -> com.mongodb.BasicDBList cannot be cast to [Ljava.lang.String;

my sample document from mongodb collection:

{    
    "_id" : ObjectId("51c7ebd9e4b096449a530024"),  
    "group_name" : "assss",  
    "privileges" : [  
        "View Log History",  
        "Communication"  
    ]  
}
1

1 Answer 1

1

The array of privileges will come back as a BasicDBList, not an array of Strings. So you can't cast it to a String[].

Instead of doing:

previliges=(String[]) f.next().get("privileges");
System.out.println(previliges.length);

Try:

BasicDBList privileges = (BasicDBList) f.next().get("privileges");
System.out.println(privileges.size());

You can iterate over this like you would over any List:

for (Object privilege : privileges) {
    String privilegeAsString = (String) privilege;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.