-1

I am trying to retrieve all Fields of all Documents and embeded Documents in Mongo collection. this is an example of one document:

{
   "_id": {
      "$oid": "53b309def468718462e0c390"
   },
   "customer": {
      "companyName": "Vins et alcools Chevalier",
      "contactName": "Paul Henriot",
   },
   "employee": {
      "employeeId": 5,
      "firstName": "Steven",
      "lastName": "Buchanan"
   },
   "orderItems": [
      {
         "productName": "Queso Cabrales",
         "unitPrice": 14,
         "quantity": 12
      },
      {
         "productName": "Singaporean Hokkien Fried Mee",
         "unitPrice": 9.8,
         "quantity": 10
      }
   ],
   "orderId": 10248,
   "orderDate": {
      "$date": "1996-07-04T07:00:00.000Z"
   },
   "requiredDate": {
      "$date": "1996-08-01T07:00:00.000Z"
   },
   "shippedDate": {
      "$date": "1996-07-16T07:00:00.000Z"
   },
   "shipVia": "Federal Shipping",
   "freightCost": 32.38
}

Here is my code and output:

MongoCursor<Document> cursor;
MongoCollection<Document> collection = database.getCollection("test");
cursor = collection.find().iterator();
try {
    while (cursor.hasNext()) {
         //System.out.println(cursor.next().toJson());
         System.out.println(cursor.next().get("key"));
    }       
} finally {
    cursor.close();
}

And this is the out put :

null null null null null ...

i want only the Name part, but it's not working.

i'm using java driver 3.12.4 with mongodb v4.2

Tank you.

1 Answers1

0

Try this:

private void printFields(){
    MongoCursor<Document> cursor;
    MongoCollection<Document> collection = database.getCollection("user");
    cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            //System.out.println(cursor.next().toJson());

            for (Map.Entry<String, Object> entry : cursor.next().entrySet())
            {
                System.out.println(entry.getKey() + "/" + entry.getValue());
            }
        }
    } finally {
        cursor.close();
    }
}
Nemanja
  • 3,295
  • 11
  • 15
  • it's not retrieve filds of embeded document, like "companyName", "contactName" of document customer. thank you – AKIMECK Aug 18 '20 at 23:28