MongoDB and Java Objects

By : Eamorr
Source: Stackoverflow.com
Question!

I have the following MongoDB object stored in my Mongo database:

array (
  '_id' => new MongoId("4cc183de48aa4c7708000000"),
  'vehicleMake' => 'Volkswagen',
  'vehicleModel' => 'Carrier',
  'vehicleNumPassengers' => '7',
  'vehicleReg' => '07-D-748393',
  'coords' => 
  array (
    0 => 
    array (
      'lat' => '53.2594946',
      'lng' => '-6.1760780',
      'timestamp' => '12345678',
    ),
    1 => 
    array (
      'lat' => '53.8994946',
      'lng' => '-6.1460780',
      'timestamp' => '12345678',
    ),
  ),
)

And in java, I can access the fields 'vehicleMake', 'vehicleModel', 'vehicleNumPassengers', 'vehicleReg' fine using the following code:

Mongo mongo=new Mongo();
DB db=mongo.getDB("garage");
DBCollection cllctn=db.getCollection("drivers");
DBCursor allDrivers=cllctn.find();

while(allDrivers.hasNext()){
    DBObject driver=allDrivers.next();
    String vehicleMake=driver.get("smsVerified").toString();
    String vehicleModel=driver.get("vehicleModel").toString();
    String vehicleNumPassengers=driver.get("vehicleNumPassengers").toString();
    String vehicleReg=driver.get("vehicleReg").toString();
    //
    //How do I access 'lat', 'lon' and 'timestamp' here????
    //    
}

My question is: how do I access the 'lat', 'lon' and 'timestamp' values inside the MongoDB array? I'm completely stumped and can't find anything on the mongodb website or on Google.

I've tried messing around with BasicDBObject but can't seem to get anything to work.

Any help greatly appreciated.

Many thanks in advance,

By : Eamorr


Answers

@Kaustubh I got it working now...

BSONObject coords=(BSONObject)driver.get("coords");
BSONObject coords_first=(BSONObject) coords.get("0");
String lat=coords_first.get("lat").toString();
String lng=coords_first.get("lng").toString();
System.out.println(lat "---" lng);

The trick was the BSONObject cast which you correctly mentioned.

By : Eamorr


This video can help you solving your question :)
By: admin