0

I have a mongodb database ("testing") which has some collections. I use one named "Pelis3" which contains documents. The documents contains the typical elements and a subdocument named "belongs to collection" where i will to access. The problem is that I only can print the 1st level elements and the subdocument like a document.

How can I get one by one the elements of the subdocument "belongs_to_collection"?

This is my java code. I call the function saveJson:

public class mongoDB {

    private MongoClient mongoClient;
    private MongoDatabase mongodb;
    private MongoCollection<Document> collection;

    public MongoDatabase selectDatabase() {
        setMongoClient(new MongoClient());
        setMongodb(getMongoClient().getDatabase("testing"));
        return getMongodb();
    }

    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public void setMongoClient(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    public MongoDatabase getMongodb() {
        return mongodb;
    }

    public void setMongodb(MongoDatabase mongodb) {
        this.mongodb = mongodb;
    }

    public MongoCollection<Document> getCollection() {
        return collection;
    }

    public void setCollection(String col) {
        this.collection = (selectDatabase().getCollection(col));
    }

    public void saveJson(JsonObject json) {
        setCollection("Pelis3");
        Document document = Document.parse(json.toString());
        getCollection().insertOne(document);

        for (Document doc : getCollection().find()) {

            System.out.println(doc.getBoolean("adult"));
            Object ob = doc.get("belongs_to_collection");
            System.out.println(ob);


        }
    }
}

This is the content of the collection:

{
  "adult": false,
  "backdrop_path": "/8SqBiesvo1rh9P1hbJTmnVum6jv.jpg",
  "belongs_to_collection": {
    "id": 304378,
    "name": "Independence Day Collection",
    "poster_path": "/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg",
    "backdrop_path": "/p7oqa94XgNGVMazXwR49QfyGgtx.jpg"
  },
  "budget": 165000000,
  "genres": [
    {
      "id": 28,
      "name": "Action"
    },
    {
      "id": 12,
      "name": "Adventure"
    },
    {
      "id": 878,
      "name": "Science Fiction"
    }
  ],
  "homepage": "http://www.warof1996.com",
  "id": 47933,
  "imdb_id": "tt1628841",
  "original_language": "en",
  "original_title": "Independence Day: Resurgence",
  "overview": "We always knew they were coming back. Using recovered alien technology, the nations of Earth have collaborated on an immense defense program to protect the planet. But nothing can prepare us for the aliens’ advanced and unprecedented force. Only the ingenuity of a few brave men and women can bring our world back from the brink of extinction.",
  "popularity": 5.163195,
  "poster_path": "/5CHJs479xWnm3zMDOl94VkKS7MZ.jpg",
  "production_companies": [
    {
      "name": "Twentieth Century Fox Film Corporation",
      "id": 306
    },
    {
      "name": "Centropolis Entertainment",
      "id": 347
    },
    {
      "name": "TSG Entertainment",
      "id": 22213
    },
    {
      "name": "Stereo D",
      "id": 86561
    }
  ],
  "production_countries": [
    {
      "iso_3166_1": "US",
      "name": "United States of America"
    }
  ],
  "release_date": "2016-06-22",
  "revenue": 389681935,
  "runtime": 120,
  "spoken_languages": [
    {
      "iso_639_1": "en",
      "name": "English"
    }
  ],
  "status": "Released",
  "tagline": "We had twenty years to prepare. So did they.",
  "title": "Independence Day: Resurgence",
  "video": false,
  "vote_average": 4.9,
  "vote_count": 2236
}

And this is the exit when I execute de program:

jfx-project-run:
Executing /media/daniel/WD_1TB/Programación/proyectos personales/Gestor de colecciones/dist/run1943415091/Gestor de colecciones.jar using platform /usr/lib/jvm/java-8-oracle/jre/bin/java
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Opened connection [connectionId{localValue:1, serverValue:50}] to 127.0.0.1:27017
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[2, 6, 10]}, minWireVersion=0, maxWireVersion=2, maxDocumentSize=16777216, roundTripTimeNanos=579216}
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Opened connection [connectionId{localValue:2, serverValue:51}] to 127.0.0.1:27017
false
Document{{id=304378, name=Independence Day Collection, poster_path=/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg, backdrop_path=/p7oqa94XgNGVMazXwR49QfyGgtx.jpg}}
false
Document{{id=304378, name=Independence Day Collection, poster_path=/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg, backdrop_path=/p7oqa94XgNGVMazXwR49QfyGgtx.jpg}}
Java Result: 1
Deleting directory /media/daniel/WD_1TB/Programación/proyectos personales/Gestor de colecciones/dist/run1943415091
jfxsa-run:
BUILD SUCCESSFUL (total time: 3 seconds)
Daniel Ruiz
  • 331
  • 1
  • 3
  • 18
  • 1
    Add `Document ob = doc.get("belongs_to_collection"); String posterPath = ob.get("poster_path");` inside for loop. – s7vr Jul 02 '17 at 22:28
  • You want serialized output? Then serialize it. `System.out.println(ob.toJson());` – Neil Lunn Jul 02 '17 at 22:31
  • @Veeram your code works well, but need a little change: Document btc = (Document) doc.get("belongs_to_collection"); String posterPath = (String) btc.get("name"); System.out.println(posterPath); Thanks. NeilLunn, I only need the values as a String. Thanks. – Daniel Ruiz Jul 02 '17 at 22:37
  • 1
    Np. Better try `Document btc = doc.get("belongs_to_collection", Document.class); String posterPath = btc.getString("name"); System.out.println(posterPath);` – s7vr Jul 02 '17 at 22:39
  • @Veeram Yes, is better. But, can you explain why Document.class? Is something like get from Document.class belongs_to_collection? – Daniel Ruiz Jul 02 '17 at 22:41
  • 1
    Its similar to what you did earlier. Instead of explicit class casting, you use helper method which behind the scene casts to Document when you use Document.class. Document is representation of complex types in MongoDB like subdocument in your case. – s7vr Jul 02 '17 at 22:44

0 Answers0