我有以下 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/