Consider this document structure (employees). It contains a reference to the department document embedded within it named "deptno" which stores a reference to the department document.
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"
}
]
}
Using the following statements to retrieve the deptno - _id field.
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)
===================
How do I retrieve the "_id" field from the deptno sub-document ?.
Made use of the following and it helped
oid = d.getEmbedded(Arrays.asList("deptno","_id"), ObjectId.class);