【问题标题】:Retrieve fields of all documents in mongodb collection检索 mongodb 集合中所有文档的字段
【发布时间】:2020-08-18 11:54:41
【问题描述】:

我正在尝试检索所有文档的所有字段并在 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 ...

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

我正在使用 java 驱动程序 3.12.4 和 mongodb v4.2

谢谢你。

【问题讨论】:

  • 尝试使用keySet()。你得到null 因为你的收藏没有名为key的字段
  • 谢谢它的工作,但它返回一个列表,以及如何一一检索排除_id

标签: java mongodb mongo-java-driver


【解决方案1】:

试试这个:

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

【讨论】:

  • 它不是检索嵌入文档的字段,例如文档客户的“companyName”、“contactName”。谢谢
猜你喜欢
  • 2020-10-02
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多