2017-04-14 52 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