检索mongodb集合中所有文档的字段

问题描述

我正在尝试检索Mongo集合中所有文档和嵌入文档的所有字段。 这是一个文档的示例:

{
   "_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
}

这是我的代码输出

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();
}

这是输出

null null null null null ...

我只需要Name部分,但是它不起作用。

我将Java驱动程序3.12.4与mongodb v4.2结合使用

给你打个招呼。

解决方法

尝试一下:

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();
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...