MongoDB Java - 嵌套json中获取ID
问题描述:
我有以下json结构。我正在尝试retreive在java中运行以下mongo查询,其中hData._id不为空。MongoDB Java - 嵌套json中获取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());
}
}
答
您可以使用Filters
和Projections
辅助方法。
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");
}
}
你有没有检查cur.next()是什么?我想你不能调用getObjectId(“hData._id”)。 – vinay
您使用的是哪个版本的mongo驱动程序? – ProgrammerBoy