0

I have a case where I need to search nearby merchants of the logged in Users's location. The user's current city's lat long to be used for comparison with the Merchant data stored in our database which is like this -

{ "merchant_id" : "W234FDHDF##234", "location" : { "loc" : {"lat" : -58.4,"lng" : 30.8},"city" : "Cupertino" , "display_address" : [ "20956 W Homestead Rd" , "Cupertino, CA 95015"] , "postal_code" : "95015" , "country_code" : "US" , "address" : [ "20956 W Homestead Rd"] , "state_code" : "CA"} }

I am new to MongoDB and do not have much idea about it. I am using mongodb API for our Java application. Can someone provide a guidance how to implement this in Java ?

1 Answers1

0

MongoDB does not care about the field names in loc. It always first uses longitude, and then latitude. You have it the wrong way around. Instead you want this:

db.col.ensureIndex( { location.loc: "2dsphere" } );

db.col.insert( { 
    "merchant_id" : "W234FDHDF##234", 
    "location" : { 
        "loc" : { type: "Point", coordinates: [ 30.8, -58.4 ] },
        "city" : "Cupertino",
    } 
} );

And then you can use a $geoNear query:

// location object
BasicDBObject myLoc = new BasicDBObject();
myLoc.append("type", "Point");
double[] loc = {-121.97679901123047,37.557369232177734}; 
// place comma in myLoc.append("coordinates", location);

myLoc.append("coordinates" , loc );

// command object
BasicDBObject myCmd = new BasicDBObject(); 
myCmd.append("geoNear", "col"); 
myCmd.append("near", myLoc); 
myCmd.append("spherical", true); 
myCmd.append("maxDistance", 50000); // in meters
System.out.println(myCmd); 
CommandResult myResults = db.command(myCmd);
zxq9
  • 13,020
  • 1
  • 43
  • 60
Derick
  • 35,169
  • 5
  • 76
  • 99