1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

BasicDBObject internally knows how to serialize any instance of Iterable.(Thus the List gets properly serialized and stored in mongo)
I am doing the very same in my above example!!! and also I copy your snippet into my code and it doesn't work
so is the array empty in mongo database after u tried the code?
hey it is working for me... can u please post the output JSON of the find() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.