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
。
请给予。
样品文档看起来喜欢 - '{ “_id”:物件( “528f37fdb55099000c5dfedd”), “ITEMNAME”: “项目1”, “ItemCategory”: “电子”, “ItemSubCategory”: “TV”, “ItemBrand”:“Samsung”, “ItemSize”:“20”, “ItemPrice”:“7500” }' –
没问题,所以''ItemCategroy“'确实是一个错字 - 修复它有帮助吗? – chk