简体   繁体   中英

Retrieve data from mongodb

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM