views:

27

answers:

2

Hi,

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,

+1  A: 

you have to do:

BasicDBObject query = new BasicDBObject();
query.put("array.lat");
collection.find(query);

or

do this:

System.out.println(cursor.next().get("coords").get("lat"));

you will also have to add a BSONObject cast to it.

EDIT: I Think the first method is incorrect. you also need a value pair to go along.

Kaustubh P
Hi, just back and thanks for your reply. I tried .get("coords").get("lat"), but it didn't work. I presume I have to do a .get("coords") to get an array and then .get("lat") on that array. But I can't figure out how to do this...
Eamorr
A: 

@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.

Eamorr
please accept my answer if you found it helpful.
Kaustubh P