从mongodb查询中获取字段值,该查询由toArray()转换

时间:2013-12-24 06:14:19

标签: android mongodb

List<?> records = collection.find(gtQuery).toArray();
System.out.println(records);
//Output
 [{ "_id" : { "$oid" : "52aad1d3e6268005b08b3276"} , "dealer_id" : "1003" , "title" : "Airtel" , "description" : "Get free talktime on topup of Rs.100" , "expiration" : { "$date" : "2014-01-01T05:00:00.000Z"}}, { "_id" : { "$oid" : "52aad1dbe6268005b08b3277"} , "dealer_id" : "1002" , "title" : "Vodafone" , "description" : "Make your own plan for you" , "expiration" : { "$date" : "2014-01-11T05:00:00.000Z"}}, { "_id" : { "$oid" : "52aad1e1e6268005b08b3278"} , "dealer_id" : "1001" , "title" : "BSNL" , "description" : "We don`t do anything" , "expiration" : { "$date" : "2015-01-01T05:00:00.000Z"}}, { "_id" : { "$oid" : "52aad1f1e6268005b08b3279"} , "dealer_id" : "1004" , "title" : "Indigo" , "description" : "Get Rs.500 off on your next flight" , "expiration" : { "$date" : "2014-06-01T04:00:00.000Z"}}, { "_id" : { "$oid" : "52aad1fbe6268005b08b327a"} , "dealer_id" : "1005" , "title" : "Flipkart" , "description" : "Free shipping on order of Rs.200 and above" , "expiration" : { "$date" : "2014-02-01T05:00:00.000Z"}}, ]

我可以使用 records.get(index)获取个人记录。但是现在如何获取特定字段的值,如dealer_id,title,description等的值?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

DBCursor cur = collection.find(gtQuery);
while(cur.hasNext()) {
   DBObject obj = cur.next();
   String dealerId = (String) obj.get("dealer_id");
   String title = (String) obj.get("title");
   String description = (String) obj.get("description");
}

如果你想获得一个列表并迭代它,那么你可以按如下方式进行:

List<DBObject> records = coll.find().toArray();
for (DBObject record : records) {
   String dealerId = (String) record.get("dealer_id");
   String title = (String) record.get("title");
   String description = (String) record.get("description");
}