Retrieve array from mongodb using java

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Previously we saw how to retrieve documents from mongodb, we will move further and understand how to retrieve array from mongodb using java.

Retrieve Array From Mongodb using Java:

Consider we have document as below in mongodb

Notice that each employee contains a field called courses which again is an array of documents where each document is a course and has fields name and type.

Now we want to retrive array from mongodb using java. Consider below code

Nothing new here, simply retrieves all employees from collection.

Now we want to retrieve all courses of each employee. We can do something like below

Note that tricky part here is you have to cast the object returned by employee.get(“courses”); into List<Document> from which you can directly iterate through and perform any operation you want. Here is the full code to retrieve array from mongodb using java

This outputs

Aug 24, 2015 12:18:12 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout=’30000 ms’, maxWaitQueueSize=500}
Aug 24, 2015 12:18:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Aug 24, 2015 12:18:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:41}] to localhost:27017
Aug 24, 2015 12:18:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 4]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=4295727}
Aug 24, 2015 12:18:13 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:42}] to localhost:27017
name = Prasad Kharkar course details below
course name = java
cours type = technical
name = Prasad Kharkar course details below
course name = dotnet
cours type = technical
name = Prasad Kharkar course details below
course name = hadoop
cours type = technical
name = Harish Taware course details below
course name = csharp
cours type = technical
name = Harish Taware course details below
course name = CS
cours type = behavioral
name = Sushant Pangarkar course details below
course name = support
cours type = technical
name = Sushant Pangarkar course details below
course name = English
cours type = behavioral
name = Sushant Pangarkar course details below
course name = Management
cours type = Management

I hope the article helped understand how to retrieve array from mongodb using java.

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

8 thoughts on “Retrieve array from mongodb using java

  • Pingback:update document in mongodb using java - theJavaGeek

  • February 26, 2016 at 6:29 am
    Permalink

    saved my day, thanks. i was trying to solve my problem with $unwind , but this resulted a great workaround

    Reply
  • April 7, 2016 at 7:21 pm
    Permalink

    List courses = (List) employee.get(“courses”);

    ———————> gives me error….can not convert from object to List of objects………
    ———————-employee.get(“courses”) returns Object..not List………………………………………….i have tried a lot but gives me errors, warnings…etc

    Reply
    • February 16, 2017 at 6:36 pm
      Permalink

      New to MongoDB and trying to use Scala Driver, same issue, the embedded Array returns as type Object and then has little to cast/convert to Document or into a class.
      I insert as a Document, so confused and struggle to find a solution to now get the data.

      On the whole struggling to find much material on Scala Driver and using it for real-world.

      Reply
      • February 17, 2017 at 12:19 am
        Permalink

        Managed to it to work.
        Basically extra and add to a mutable list x.asDocument.
        The document type is Bson not the scala type, but can extract into the class.

        Reply
  • October 6, 2016 at 12:15 pm
    Permalink

    I use this code in java using netbeans this code is running, but in jsp i have error in the line

    List documents = (List) collection.find().into(
    new ArrayList());

    documents.stream().forEach((Document document) {
    System.out.println(document);

    Reply
  • October 9, 2018 at 4:42 pm
    Permalink

    This does the processing on the client side, Unwind does the same on the server side. This is hence slower way to retrieve the same object

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *