Reputation: 10022
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,
Upvotes: 1
Views: 3248
Reputation: 10022
@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.
Upvotes: 2
Reputation: 13879
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.
Upvotes: 4