-1

Given this document:

Document{{
     _id=5a66fceba07b4ba90a19ee07, 
     address=Document{{
          building=8405,
          coord=[-74.02521709999999, 40.6224629],
          street=5 Avenue, zipcode=11209
     }},
     borough=Brooklyn, 
     cuisine=Chinese,
     grades=[
          Document{{date=Tue Feb 25 05:30:00 IST 2014,grade=A, score=12}},
          Document{{date=Wed Aug 14 05:30:00 IST 2013, grade=C, score=28}},
          Document{{date=Wed Jul 18 05:30:00 IST 2012, grade=A,score=13}}, 
          Document{{date=Fri Mar 09 05:30:00 IST 2012, grade=A, score=13}}, 
          Document{{date=Thu Oct 27 05:30:00 IST 2011, grade=A, score=12}},  
          Document{{date=Thu May 19 05:30:00 IST 2011, grade=A, score=13}}
     ],
     name=Chopstix Restaurant, restaurant_id=40900694
}}

I want to display the sub document in the address field.

How can I display it using Java MongoDB driver 3.6.1?

glytching
  • 44,936
  • 9
  • 114
  • 120
yash vaidya
  • 9
  • 1
  • 4

1 Answers1

0

To read a sub document (or any attribute of a document) using the Mongo Java driver, you use Projections in conjunction with collection.find() ...

collection.find().projection(fields(include("x", "y"), excludeId()))

Here's an example based on the document shown in your question:

MongoClient mongoClient = ...;

MongoCollection<Document> collection = mongoClient.getDatabase(databaseName).getCollection(collectionName);

FindIterable<Document> documents = collection
        // create the predicates i.e. the 'where' clause
        .find(Filters.and(
                Filters.eq("address.street", "5 Avenue"),
                Filters.eq("address.zipcode", 11209),
                Filters.eq("cuisine", "Chinese")
        ))
        // create the projection(s) i.e. the select clause
        .projection(Projections.include("address"));

for (Document document : documents) {
    System.out.println(document.toJson());
}

More details in the docs, specifically the sections titled:

  • Projecting fields
  • Get A Single Document with a Query Filter
  • Get A Set of Documents with a Query
glytching
  • 44,936
  • 9
  • 114
  • 120