I am trying to create a route to retrieve the records with nearby location coordinates.
I checked the logs and found the "docs" value as undefined. What am I going wrong with?
router.get('/userlist/:lat/:lng', function (req, res) {
var db = req.db;
var lat = req.params.lat, lng = req.params.lng;
console.log("lat "+lat);
console.log("lng "+lng);
var collection = db.get('userlist');
collection.find({
"location": {
$nearSphere: {
$geometry: {
type: "Point" ,
coordinates: [ lat , lng ]
}
}
}
}, {}, function (e, docs) {
docs = JSON.stringify(docs);
console.log("docs "+docs);
res.send(docs);
});
});
I am storing the JSON data as shown in the screenshot below.
The location should be stored in the format:-
"location" : {
"type" : "Point",
"coordinates" : [
-70.845654,
42.146249
]
}
The geojson point should be an object and not an array.
As #Webdev said, the coordinates are stored as strings and shall not be. But I was unable to store them in numeric form using mongoose. So I am parsing the latitude and the longitude into float in the find query itself and it works.
Related
I have field location array for coordinates
{
location: [13.3339, 80.1943],
...someOtherfield
}
can I use $near in mongoose with that data? specifically in mongoose aggregate?
or I must change data field like this
{
location: {
type: { type: 'Point' },
coordinates: [13.3339, 80.1943],
},
}
Your document implies that you are storing location using Legacy Coordinate Pairs
location: [<longitude>, <latitude> ]
Yes, you can use $near with your data, if you have 2d index, on your location field. 2d index
After that, You can query like this
db.collection.find(
{ location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)
You can refer it from here
Say I have a collection with entries like so:
{_id: "foo" lng: -98.21 lat: 77.131 }
{_id: "foo" lng: -100.12 lat: 770.313 }
{_id: "foo" lng: -98.32 lat: 772.123 }
where lng and lat correspond to the longitude and latitude.
I want to return only the entries that are within a certain radius of the the input longitude and latitude. So that would mean that for radius R, sqrt((inputLatiude - docLatitude)^2 + (inputLongitude - docLonguitude)^2) < R.
I don't want to return all the documents with an added field that tells me whether it's within R or not. I want to return only the fields that match the condition.
How do I query this?
You'll want to use $near here to do so. However $near requires a 2dsphere index built which currently seems like you don't have one as the document structure does not match the required structure.
So what do you have to do?
Restructure your document so the lng and lat fields could be 2dsphere indexed:
{
_id: "foo",
loc : { type: "Point", coordinates: [ -98.21, 77.131 ] },
}
Build such index on the field loc.
Use $near to query:
db.collection.find(
{
loc:
{ $near :
{
$geometry: { type: "Point", coordinates: [ inputLng, inputLat ] },
$maxDistance: R
}
}
}
)
I have this structure in my collection
{
"categorie" : "Introduction",
"quart" : "jour",
"pdq" : 23,
"x" : 302375.197993,
"y" : 5046522.11601,
"lat" : 45.5586064034326,
"long" : -73.5310596776929,
"date" : ISODate("2015-01-01T00:00:00Z"),
}
I have latitude=42.5232886&longitude=-71.5923142 in query parameters.
I need to find all documents which are located at less than 3KM from the a coordinate point passed in parameter.
I am using MongoDB 3.6
Actually we don't need Haversine formula in Mongodb.Here I have done with mongoose. We need to create a schema that contain type and coordinates. You can see more details in https://mongoosejs.com/docs/geojson.html
So it's has another problem with mongoose version. Mongoose v6.3.0
worked for me. When you will use countDocuments with the query, it can
be generate error but count function not generating any error. I know
count deprecated, it shouldn't be use but I haven't find better
solution. If anyone find solution for count, let me know. Also you can visit https://github.com/Automattic/mongoose/issues/6981
const schema = new mongoose.Schema(
{
location: {
type: {
type: String,
enum: ["Point"],
},
coordinates: {
type: [Number],
index: "2dsphere",
},
},
},
{ timestamps: true }
);
const MyModel = mongoose.model("rent", schema);
The query will be
const result = await MyModel.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [Number(filters.longitude), Number(filters.latitude)],
},
$maxDistance: filters.maxRadius * 1000,
$minDistance: filters.minRadius * 1000,
},
},
})
i want to find near by location so inserting record like this..
db.locationcol.insert({"location":"phase 8,mohali ,punjab ,india","service":"psychologist","loc":{"lon":76.703347,"lat":30.710459}})
and then executing Query on terminal .
db.runCommand(
{
geoNear: "locationcol",
near: { type: "Point", coordinates: [ 76.720845, 30.712097 ] },
spherical: true,
query: { category: "public" }
})
but it is returning ..
{ "ok" : 0, "errmsg" : "no geo indices for geoNear" }
i am also trying it with Spring ...
public GeoResults getnearby(double longitude,double latitude, String service) {
Point point = new Point(longitude,latitude);
Query query = new Query(Criteria.where("service").is(service));
query.fields().include("service").include("location").include("loc");
NearQuery nearQuery = NearQuery.near(point).maxDistance(new Distance(50, Metrics.KILOMETERS));
nearQuery.query(query);
nearQuery.num(20);
GeoResults<locationcol> data = operations.geoNear(nearQuery, locationcol.class,"locationcol");
return data;
}
this code is returning empty list .i am not getting that where i am going wrong. help !!
Before you can execute geospatial queries, you need to create a geospatial index:
db.locationcol.createIndex( { loc : "2dsphere" } )
Also, you need to store your locations as valid GeoJSON objects so MongoDB can parse them properly:
loc : { type: "Point", coordinates: [ -76.703347, 30.710459 ] },
mongo 2.6
I have some amount of stored polygons. And I have a point. I what to know if this point fits any of stored polygons
document example
{ ..., "polygons" : [ [ 17.60083012593064, 78.18557739257812 ], [ 17.16834652544664, 78.19381713867188 ], [ 17.17490690610013, 78.739013671875 ], [ 17.613919673106714, 78.73489379882812 ] ], ... }
There is nearly the same question already Mongodb : Check if a point is inside a stored polygon.
But it is not working for me - this query has to give at least one result(the one in example) - but it does not.
db.areas.find( { polygons : { $geoIntersects : { $geometry : {type:"Point",coordinates:[17.3734, 78.4738]} } } } )
Actually if I chose a point on a border of any polygon - it does.
$geoWithin method has to do the work as mondodb documentation says.
but any of these queries do not work
db.areas.find( { polygons : { $geoWithin : { $geometry : {type:"Point",coordinates:[17.3734, 78.4738]} } } } ) - not supported with provided geometry
db.tradeareas.find( { polygons : { $geoWithin : { $geometry : {type:"Polygon",coordinates: inside_polygon} } } } ) - BadValue bad geo query
It seems I miss something but cant understand what and where.
I would be grateful for help.
It seems to be to do with the order. If you are using $geoWithin and you are trying to find points inside a polygon, the thing that is within is the field you are searching on. However, $geoIntersects works in either direction, so you can search for points inside polygons, or polygons containing points, eg:
db.geom.insert({
"polygons": {
"type":"Polygon",
"coordinates": [[
[ 17.60083012593064, 78.18557739257812],
[ 17.16834652544664, 78.19381713867188],
[ 17.17490690610013, 78.739013671875],
[ 17.613919673106714, 78.73489379882812],
[ 17.60083012593064, 78.18557739257812]
]]
}
});
db.geom.find({
polygons: {
$geoIntersects: {
$geometry: {
"type": "Point",
"coordinates": [17.3734, 78.4738]
}
}
}
});
Also, note that, you need to repeat the first point of the polygon at the end. If you remove the final pair, you will get a $err:
Can't canonicalize query: BadValue bad geo query" error.
It seems that MongoDB allows you to insert invalid geometries and only complains when you try and add a 2dsphere index or do an intersects/within/near query, which, I suppose is reasonable, as GeoJSON can be valid JSON without being a valid geometry.
Thanks for John Powell here is C# driver version of the same query.
var geometry = new BsonDocument
{
{ "type", "Point" },
{ "coordinates",
new BsonArray(new double[]{ Longitude,
Latitude} ) }
};
var geometryOperator = new BsonDocument { { "$geometry", geometry } };
var geoIntersectsOperator = new BsonDocument { { "$geoIntersects", geometryOperator } };
var findField = new BsonDocument { { "geometry", geoIntersectsOperator } };
var results = MyCollection.Find(findField).ToList();
In Java it Can be done this way
#Autowired
private MongoOperations mongoOpertions;
public void pointIntersect(GeoJsonPoint gp){
Query query = new Query();
query.addCriteria(Criteria.where("geometry").intersects(gp));
List<ResultDtoType> result = mongoOpertions.find(query, ResultDtoType.class);
//perform any action with result
}