我是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()
方法中传递category
并希望返回的数组ItemNames
中的所有prodName
。
请suugest。
答案 0 :(得分:0)
你能说出究竟什么不起作用吗?您是否观察到错误或者根本没有匹配?可能只是由于BasicDBObject query = new BasicDBObject("ItemCategroy", category);
中的拼写错误,您可能应该写ItemCategory
。
除此之外,你的代码看起来还不错,但我们当然不能确定,除非你发布你的收藏的样本文件。