Vahid Hashemi
Vahid Hashemi

Reputation: 5240

how to store array in mongodb?

I want to store a simple array of latitude,longitude inside a mongoDB collection using java and I am using following code but my "loc" array always is empty :

BasicDBObject doc = new BasicDBObject();
//doc.put("key " , r.getKey());
doc.put("category" , r.getKey());
doc.put("type" , r.getValue());

BasicDBObject latlon = new BasicDBObject();


ArrayList<Float> aLatLong = new ArrayList<Float>();

{




    Float fLat = Float.parseFloat(r.getLatitude());
    Float fLon = Float.parseFloat(r.getLongitude());
    aLatLong.add(fLat);
    aLatLong.add(fLon);

    latlon.put("lat" , fLat);
    latlon.put("lon" , fLon);
}


doc.put( "loc" , aLatLong);

but when I don't use ArrayList at all and try to store latlon into "loc" it will show me the data but its not an array anymore.

how can I save a simple array in mongoDB?

Upvotes: 1

Views: 7736

Answers (2)

Byter
Byter

Reputation: 1132

All you need to do is this :

BasicDBObject doc = new BasicDBObject();

doc.put("category" , r.getKey());
doc.put("type" , r.getValue());

List<Float> aLatLong = new ArrayList<Float>();

Float fLat = Float.parseFloat(r.getLatitude());
Float fLon = Float.parseFloat(r.getLongitude());
aLatLong.add(fLat);
aLatLong.add(fLon);

doc.put( "loc" , aLatLong);

now use the insert method of mongodb to save the DBObject.

Upvotes: 1

Abhishek bhutra
Abhishek bhutra

Reputation: 1422

Try this

BasicDBObject doc = new BasicDBObject();
//doc.put("key " , r.getKey());
doc.put("category" , r.getKey());
doc.put("type" , r.getValue());

java.util.Map<String,Float> latLongMap = new java.util.HashMap<String,Float>();
latLongMap.put("lat" , Float.parseFloat(r.getLatitude());
latLongMap.put("lon" , Float.parseFloat(r.getLongitude());

doc.put( "location" , latLongMap);

This will store a json of lat-long. Also if you want to store them as array, that is also possible but i will suggest you store them as this.

Upvotes: 2

Related Questions