isudansh
isudansh

Reputation: 369

Get field values from a mongodb query which is converted by toArray()

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"}}, ]

I can get individual record by using records.get(index). But now how do I get the values of a specific field, like value of dealer_id,title,description etc?

Upvotes: 1

Views: 181

Answers (1)

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

You can do it as :

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");
}

If you want to get a list and iterate though it, then you can do it as follows :

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");
}

Upvotes: 1

Related Questions