java - MongoDB Java - 在嵌套 json 中获取 id

标签 java mongodb mongodb-query spring-data-mongodb

我有以下 json 结构。我正在尝试在 java 中检索运行以下 mongo 查询,其中 hData._id 不为空。

MongoDb Query: db.Collection.find({},{"hData._id":1, "hData.createdBy":1} )

{
    "_id" : ObjectId("55567e594e3256a23565ce58"),
       "hData" : {
        "isDeleted" : false,
        "canDelete" : false,
        "canUpdate" : false,
        "createdBy" : “xyz”,
        "createdDate" : "2015-05-15T15:05:30",
        "_id" : "7"
    },
    "changeDate" : "2015-02-19T16:02:12",

}

我用java编写的用于获取hData._id的代码是

MongoCursor<Document> cur = col.find(new BasicDBObject("hData._id", new BasicDBObject("$ne",null)))).iterator();
        try{
            while(cur.hasNext()){
                System.out.println(cur.next().getObjectId("hData._id"));
                i++;
            }
        }finally {
            cur.close();
        }

但是,hData._id 返回为 null。你能帮我解决这个问题吗?

最佳答案

您无法使用点表示法获取嵌套属性,例如x.y

因此,在您的示例中,您需要首先获取 hData,然后在 _id 上调用 get。像这样:

    MongoCursor<Document> cur = col.find(new BasicDBObject("hData._id", new BasicDBObject("$ne",null))).iterator();

    while(cur.hasNext()){
        System.out.println(cur.next().get("hData", Document.class).getString("_id"));
    }

另请注意,在您的示例中 hData._id 显示为字符串而不是 ObjectId,因此在我的示例中我使用了 getString()

编辑 因为听起来您可能有 hData._id 的混合类型,这里有一个更强大的示例,其中包含类型检查和一些额外的调试输出来说明:

    MongoCursor<Document> cur = col.find(new BasicDBObject("hData._id", new BasicDBObject("$ne",null))).iterator();

    while(cur.hasNext()){
        Document doc = cur.next();
        System.out.println("Document _id" + doc.get("_id"));
        Document hdata = doc.get("hData", Document.class);
        Object id = hdata.get("_id");
        System.out.println("hData._id " + id);

        // check type if you need to
        if (id instanceof String) {
            System.out.println("hData._id is String: " + id);
        } else if (id instanceof ObjectId) {
            System.out.println("hData._id is ObjectId: " + id);
        } else {
            System.out.println("hData._id is of type " + id.getClass().getName());
        }
    }

关于java - MongoDB Java - 在嵌套 json 中获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43414157/

相关文章:

java - 从已登录的 Windows 中获取用户名?对于我的 Swing 申请

python - 如何将 MongoDB 与 Keras 的 Sequence 类或生成器一起使用?

javascript - 为什么我的 Mongoose 数组没有被填充,甚至没有存储值?

mongodb - 删除 MongoDB 中的重复项

json - mongo 2.6.4 中的多个 $near 不起作用

mongodb - 如何聚合集合并查找最小/最大值

java - 查找定位器 Selenium Webdriver - IE8 时遇到问题。无法浏览菜单

java - 光滑2d | TextField 字符传递

java - 如何仅在使用spring单击java中的提交按钮后才转到下一页

java - 在 MongoDB 中强制执行模式验证