Reputation: 5444
I've got a mongodb database and I want to retrieve data from java mongodb API. My database is like the following json:
{
"_id": 123456,
"value": {
"count": 123,
"persons": 456
}
}
I want to perform queries for specific id in order to get count and persons. My code is:
BasicDBObject query = new BasicDBObject("_id", no);
DBCursor cursor = coll_in.find(query);
System.out.println(cursor);
I found the object in database with find(query) and I want to retrieve count value and persons.
Upvotes: 0
Views: 621
Reputation: 1460
The cursor what you are getting from DB with coll_in.find(query)
can be a set of documents or you need to use *.findOne()
or with your variant do like this:
try (DBCursor cursor = coll_in.find(query)) {
while (cursor.hasNext()) {
final DBObject result = cursor.next();
Map<String, Object> value = (Map<String, Object>) result.get("value");
System.out.println(value.get("count"));
System.out.println(value.get("persons"));
}
} catch (final MongoException ex) {
// error
}
But to minimize your code use findOne()
if you sure that you have unique _id.
Upvotes: 2
Reputation: 5817
Example for findOne() method
BasicDBObject query = new BasicDBObject("_id", no);
DBObject object = coll_in.findOne(query);
Map<String, Object> doc = (Map<String, Object>) object;
if(doc != null) {
Map<String, Object> value = (Map<String, Object>) doc.get("value");
System.out.println(value.get("count"));
System.out.println(value.get("persons"));
}
Upvotes: 1