MongoDB 从嵌套文档中读取
MongoDB Reading from Nested Documents
我有一个包含嵌套文档的文档,我认为根据过滤器我可以指定类似 data.sms.mobileNumber 的内容。然而那是行不通的。
如何使用标准文档 getString 请求读取 data.sms.mobileNumber 字段中的数据?
示例文档:
{ "_id" : ObjectId("59b850bd81bacd0013d15085"), "data" : { "sms" : { "message" : "Your SMS Code is ABCDEFG", "mobileNumber" : "+447833477560" } }, "id" : "b0a3886d69fc7319dbb4f4cc21a6039b422810cd875956bfd681095aa65f6245" }
示例字段获取字符串请求:
document.getString("data.sms.message")
'path'data.sms.message
指的是这样的结构:
+- data
|
+- sms
|
+- message
要使用 Java 驱动程序阅读此内容,您必须阅读 data
文档,然后是 sms
子文档,然后是该子文档的 message
属性。
例如:
Document data = collection.find(filter).first();
Document sms = (Document) data.get("sms");
String message = sms.getString("message");
或者,与快捷方式相同:
String message = collection.find(filter).first()
.get("sms", Document.class)
.getString("message");
更新 1 回答这个问题:"I have a case where I have an array of documents in a document, how would I go about getting a field from a document in the array?" 假设您有一个文档,其中包含一个名为 details
的数组字段,每个 detail
有 name
和 age
。像这样:
{"employee_id": "1", "details": [{"name":"A","age":"18"}]}
{"employee_id": "2", "details": [{"name":"B","age":"21"}]}
您可以像这样读取数组元素:
Document firstElementInArray = collection.find(filter).first()
// read the details as an Array
.get("details", ArrayList.class)
// focus on the first element in the details array
.get(0);
String name = firstElementInArray.getString("name");
我有一个包含嵌套文档的文档,我认为根据过滤器我可以指定类似 data.sms.mobileNumber 的内容。然而那是行不通的。
如何使用标准文档 getString 请求读取 data.sms.mobileNumber 字段中的数据?
示例文档:
{ "_id" : ObjectId("59b850bd81bacd0013d15085"), "data" : { "sms" : { "message" : "Your SMS Code is ABCDEFG", "mobileNumber" : "+447833477560" } }, "id" : "b0a3886d69fc7319dbb4f4cc21a6039b422810cd875956bfd681095aa65f6245" }
示例字段获取字符串请求:
document.getString("data.sms.message")
'path'data.sms.message
指的是这样的结构:
+- data
|
+- sms
|
+- message
要使用 Java 驱动程序阅读此内容,您必须阅读 data
文档,然后是 sms
子文档,然后是该子文档的 message
属性。
例如:
Document data = collection.find(filter).first();
Document sms = (Document) data.get("sms");
String message = sms.getString("message");
或者,与快捷方式相同:
String message = collection.find(filter).first()
.get("sms", Document.class)
.getString("message");
更新 1 回答这个问题:"I have a case where I have an array of documents in a document, how would I go about getting a field from a document in the array?" 假设您有一个文档,其中包含一个名为 details
的数组字段,每个 detail
有 name
和 age
。像这样:
{"employee_id": "1", "details": [{"name":"A","age":"18"}]}
{"employee_id": "2", "details": [{"name":"B","age":"21"}]}
您可以像这样读取数组元素:
Document firstElementInArray = collection.find(filter).first()
// read the details as an Array
.get("details", ArrayList.class)
// focus on the first element in the details array
.get(0);
String name = firstElementInArray.getString("name");