簡體   English   中英

檢索 mongodb 集合中所有文檔的字段

[英]Retrieve fields of all documents in mongodb collection

我正在嘗試檢索所有文檔的所有字段並在 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
}

這是我的代碼和 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();
}

這是輸出:

null null null null null ...

我只想要名稱部分,但它不起作用。

我正在使用 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM