2017-04-14 108 views
0

我有以下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。你能帮我解决这个问题吗?

+0

你有没有检查cur.next()是什么?我想你不能调用getObjectId(“hData._id”)。 – vinay

+0

您使用的是哪个版本的mongo驱动程序? – ProgrammerBoy

回答

1

您不能使用点符号来获取嵌套属性,例如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()); 
     } 
    } 
+0

谢谢@helmy,你救了我的周末。 – Saurabh

+0

嗨@helmy - 我仍然得到某些行 - ObjectId不能转换为java.lang.string – Saurabh

+0

看起来像你的数据中有混合类型。可能希望保持数据的一致性。无论如何,我已经增加了另一个关于如何检查和处理值的不同类型的例子。 – helmy

1

您可以使用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"); 
     } 
    } 
+0

谢谢@Veeram,我该如何处理-ObjectId不能转换为java.lang.string? – Saurabh

+0

Np。是所有的ID的对象ID?如果是,则使用ObjectId id = hData.getObjectId(“_ id”)'或者先修复数据。 – Veeram