2013-12-18 47 views
0

我是mongodb初学者。使用java查询mongodb文档

我将ItemName和ItemCategory存储为文档。使用Java我想找到在方法中传递的ItemCategory的所有ItemNames。

我试过下面的代码,但它不工作。

public String[] generate(String category) { 

    MongoClient mongoClient; 
    String temp[] = new String[50001]; 
    String[] prodName = {}; 
    int i = 0, j = 0; 
    int k=0; 
    try { 
     mongoClient = new MongoClient("localhost", 27017); 
     DB db = mongoClient.getDB("test"); 
     DBCollection coll = db.getCollection("products"); 
     DBCursor cursor = coll.find(); 
     BasicDBObject query = new BasicDBObject("ItemCategroy", category); 

     cursor = coll.find(query); 

     try { 
      while (cursor.hasNext()) { 
       temp[i++] = (String) cursor.next().get("ItemName"); 
      } 
      for (k = 0; k < temp.length; k++) { 
       if (temp[k] == null) { 
        k++; 
       } else{ 
        prodName[j++]=temp[k]; 
       } 
      } 
      System.out.println("kkk"+k); 
      /* for (int j = 0; j < nodeNm.length; j++) { 
       System.out.println("printing in jsp " + nodeNm[j]); 
      } */ 
     } finally { 
      cursor.close(); 
     } 

     mongoClient.close(); 
    } catch (UnknownHostException e) { 
     e.printStackTrace(); 
    } 
    return prodName; 
} 

在这里generate()方法,我在一个阵列prodName它返回经过category并希望所有的ItemNames

请给予。

回答

0

你能说出什么是不工作?你是否观察到错误或者没有匹配?这可能只是由于BasicDBObject query = new BasicDBObject("ItemCategroy", category);中的错字,你可能应该写ItemCategory

除此之外,您的代码对我来说看起来不错,但我们当然无法确定,除非您发布了您的集合的示例文档。

+0

样品文档看起来喜欢 - '{ “_id”:物件( “528f37fdb55099000c5dfedd”), “ITEMNAME”: “项目1”, “ItemCategory”: “电子”, “ItemSubCategory”: “TV”, “ItemBrand”:“Samsung”, “ItemSize”:“20”, “ItemPrice”:“7500” }' –

+0

没问题,所以''ItemCategroy“'确实是一个错字 - 修复它有帮助吗? – chk