Find documents in mongoDB collection by coordinates via haversine formula - mongodb

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,
},
},
})

Related

Search MongoDB by closest region based on coordinates

I'm using MongoDB to store about 1 million documents representing regions.
Each document contains a coordinates record in the following format
"coordinates" : {
"longitude" : -77.02687,
"latitude" : 38.888565
}
Given a set of coordinates { x, y }, what query should I run to find the region ( document ) that is closest to it?
Based on the MongoDB geospatial-queries documentation the answer is quite simple.
In order to query for locations near a region you should follow these steps
Step 1
Create an index on the location field
db.places.createIndex( { location: "2dsphere" } )
Step 2
Find regions close to { -73.9667, 40.78 } ordered by closest locations
db.places.aggregate( [
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
spherical: true,
query: { category: "Parks" },
distanceField: "calcDistance"
}
}
] )

Mongo geoNear Aggregation Pipeline - 'near' field must be point

I am using a Mongo pipeline within an aggregation lookup on 2 collections, Locations and Places.
I am trying to return all the places which these locations are near.
The error I get is 'MongoError: 'near' field must be point'
I believe this is because I am trying to use the $point variable in the pipeline from the let in the lookup and I am doing something wrong here. All the answers I see on here have static coordinates but I want to use the ones from the lookup.
This is the code I have:
return await this.placeModel.aggregate([{
$lookup : {
from : "locations",
let : {point : "location.coordinates"},
pipeline: [ {
$geoNear: {
distanceField: "distance",
near: { type: "Point", coordinates: "$point" },
maxDistance: 20,
spherical: true
}
}],
as : "places"
}
}]);
}
I have a mongoose Place model and Location model. Each model has a GeoJson point that looks like this:
location: {
type: { type: String },
coordinates: []
},
How do I reference the point properly if at all possible.

Performance when filtering after $geoNear query

I have a MongoDB collection which contains a location (GeoJSON Point) and other fields to filter on.
{
"Location" : {
"type" : "Point",
"coordinates" : [
-118.42359,
33.974563
]
},
"Filters" : [
{
"k" : 1,
"v" : 5
},
{
"k" : 2,
"v" : 8
}
]
}
My query uses the aggregate function because it performs a sequence of filtering, sorting, grouping, etc... The first step where it's filtering is where I'm having trouble performing the geo near operation.
$geoNear: {
spherical: true,
near: [-118.236391, 33.782092],
distanceField: 'Distance',
query: {
// Filter by other fields.
Filters: {
$all: [
{ $elemMatch: { k: 1 /* Bedrooms */, v: 5 } }
]
}
},
maxDistance: 8046
},
For indexing I tried two approaches:
Approach #1: Create two separate indexes, one with the Location field and one with the fields we subsequently filter on. This approach is slow, with very little data in my collection it takes 3+ seconds to query within a 5 mile radius.
db.ResidentialListing.ensureIndex( { Location: '2dsphere' }, { name: 'ResidentialListingGeoIndex' } );
db.ResidentialListing.ensureIndex( { "Filters.k": 1, "Filters.v": 1 }, { name: 'ResidentialListingGeoQueryIndex' } );
Approach #2: Create one index with both the Location and other fields we filter on. Creating the index never completed, as it generated a ton of warnings about "Insert of geo object generated a high number of keys".
db.ResidentialListing.ensureIndex( { Location: '2dsphere', "Filters.k": 1, "Filters.v": 1 }, { name: 'ResidentialListingGeoIndex' } );
The geo index itself seems to work fine, if I only perform the $geoNear operation and don't try to query after then it executes in 60ms. However, as soon as I try to query on other fields after is when it gets slow. Any ideas would be appreciated on how to set up the query and indexes correctly so that it performs well...

how store latitude and longitude in mongodb collection? and How to use it with Spring?

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 ] },

Mongoose query for Lat/Lng in Range

I am trying to query for data points within a given lat/lng range. Can you reference the elements of an object in a mongoose query like I have done ('location.lat') and ('location.long')? If so, I am not getting any data back from this query. I was querying for all data points, and that was working just fine - now I am simply trying to refine the query to only the points in a given range.
EDIT
Querying for points that have a new format (see the updated schema below):
var range = {"topLeft":[-113.51526849999999,53.24204911518776],"bottomRight":[-131.0933935,41.397215826886736],"topRight":[-131.0933935,53.24204911518776],"bottomLeft":[-113.51526849999999,41.397215826886736]};
db.datapoints.find({
geo: {
$geoWithin : {
$geometry: {
type: "Polygon",
coordinates: [
[
range.topLeft, range.topRight, range.bottomRight, range.bottomLeft
]
]
}
}
}
})
but I am getting:
error: {
"$err" : "Malformed geo query: { $geoWithin: { $geometry: { type: \"Polygon\", coordinates: [ [ [ -113.5152685, 53.24204911518776 ], [ -131.0933935, 53.24204911518776 ], [ -131.0933935, 41.39721582688674 ], [ -113.5152685, 41.39721582688674 ] ] ] } } }",
"code" : 16677
}
NOTE: the range parameter looks like this:
UPDATED SCHEMA
var mongoose = require('mongoose');
var dataPointSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
geo: {type: [Number], index: '2d'},
...
timestamp: {type: Date, default: Date.now}
...
});
As seen here:
MongoDB: "Malformed geo query" with $geoIntersect on a polygon
You must close the polygon by making the first and last points the same.