MongoDB Java - 在嵌套中获取 id json

MongoDB Java - Fetching id in nested json

我有以下 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 上调用获取。像这样:

    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());
        }
    }

您可以使用 FiltersProjections 辅助方法。

  try (MongoCursor<Document> cur  = coll.find(Filters.ne("hData._id", null)).projection(Projections.include("hData._id", "hData.createdBy")).iterator()) {
         while(cur.hasNext()){
              Document doc = cur.next();
              Document hData = doc.get("hData", Document.class);
              String id = hData.getString("_id");
              String createdBy = hData.getString("createdBy");
        }
   }