使用 Java 驱动程序方法检索 MongoDB 子文档的 ObjectID

Retrieving ObjectID on MongoDB sub-document using Java driver methods

考虑这个文档结构(员工)。它包含对嵌入其中名为 "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)
===================

如何从 deptno 子文档中检索“_id”字段?。

你快到了...

问题是

oid = d.getObjectId("deptno");

这将 return Document 对象,而不是 ObjectId。因此,抛出了异常。

因此,将其替换为:

oid = d.get("deptno",Document.class).getObjectId("_id");

希望这会有所帮助:)

使用了以下内容,它帮助了

oid = d.getEmbedded(Arrays.asList("deptno","_id"), ObjectId.class);