1

When I try to put this type1 array from mongoDB document , I can take that as an array through java by doing code like :

BasicDBList listEditionsAssets = (BasicDBList) nextAssets.get("areas");

following is type1 array :

{
 "ClientId" : "212",
 "UserId" :"212",
 "areas" : [
   {
     "Area 1" : "Chicago"
     "Area 2" : "LA",
     "Area 3" : "Boston" 
  ]
}

But,following is the data I have in mongoDB document :

following is 'type2' array :

{
 "ClientId" : "212",
 "UserId" :"212",
 "areas" : ["Chicago","LA","Boston" ]
} 

When I try to retrieve "areas" array in java by using BasicDBList, it comes as "null". Because java is taking it as String. When I take it as

BasicDBObject result = (BasicDBObject) it.next();
String areas = (String) result.get("areas");

I can read is as String.

So how can I read "areas" in type2 document as an Array in java and not the String ?

3
  • Are you sure type2.areas is an array? I've tested on my local with mongo-java-driver 3.4.2. It does return a list with (List) dbObject.get("areas") Commented Mar 23, 2017 at 12:13
  • My object -> { "areas" : ["1", "2"] } and the result of above get with list casting -> ["1", "2"] Commented Mar 23, 2017 at 12:25
  • Hi, I am getting List as "null". I tried to take it as String and it shows the result.. BasicDBObject result = (BasicDBObject) it.next(); String areas = (result.getString("areas")); System.out.println(areas); Can't guess why getting the List null...can you please suggest have any idea? Commented Mar 24, 2017 at 11:02

1 Answer 1

1

The only significant difference between reading an array and reading a document is that, since the elements of an array do not have names, there is no field name to read, only a series of values:

reader.readStartArray();

while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
    switch (reader.getCurrentBsonType()) {
        case INT32:
            int intValue = reader.readInt32();
            break;
        case INT64:
            long longValue = reader.readInt64();
            break;
        // ... handle each supported field type
    }
}

reader.readEndArray();
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.