Рассмотрим структуру этого документа (сотрудники). Он содержит ссылку на документ отдела, встроенный в него с именем «deptno», в котором хранится ссылка на документ отдела.
ali@MongoDB>db.employees.find().pretty()
{
"_id" : ObjectId("5e907ad23997181dde06e8fc"),
"empno" : 7839,
"ename" : "KING",
"mgrno" : 0,
"hiredate" : "1990-05-09",
"sal" : 100000,
"deptno" : {
"_id" : ObjectId("5e9065f53997181dde06e8f8")
},
"username" : "none",
"password" : "none",
"is_admin" : "N",
"is_approver" : "Y",
"is_manager" : "Y",
"user_role" : "AP",
"admin_approval_received" : "Y",
"active" : "Y",
"created_date" : "2020-04-10",
"updated_date" : "2020-04-10",
"application_usage_log" : [
{
"logged_in_as" : "AP",
"log_in_date" : "2020-04-10"
}
]
}
Использование следующих операторов для извлечения поля deptno - _id.
FindIterable<Document> docs = emp_collection.find();
for (Document d : docs)
{
System.out.println("Employee Details ...");
System.out.println("Employee # : " + d.getDouble("empno"));
System.out.println("Employee Name : " + d.getString("ename"));
System.out.println("Manager # : " + d.getDouble("mgrno"));
System.out.println("Hiredate : " + d.getString("hiredate"));
System.out.println("Salary : " + d.getDouble("sal"));
//Retrive the department details using the ObjectId stored in the Employee document.
oid = d.getObjectId("deptno");
query = eq("_id",oid);
FindIterable<Document> dept_docs = dept_collection.find(query);
This statement -- oid = d.getObjectId("deptno")-- produces an error saying , although getObjectId() is designated to return ObjectId.
==================
Exception in thread "main" java.lang.ClassCastException: class org.bson.Document cannot be cast to class org.bson.types.ObjectId (org.bson.Document and org.bson.types.ObjectId are in unnamed module of loader 'app')
at org.bson.Document.getObjectId(Document.java:323)
at MongoDBExample.main(MongoDBExample.java:45)
===================
Как извлечь поле "_id" из поддокумента deptno?