Mongoose query for Lat/Lng in Range - mongodb

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.

Related

how to use mongoose $near? (type data location)

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

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.

Find documents in mongoDB collection by coordinates via haversine formula

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

Insert geojson polygons into mongodb and query, based on the coordinates of a point, all the polygons which are located at a certain distance from it

I need some help on: how to insert geojson polygons into a mongodb database and query, based on the coordinates of a certain point, all the polygons which are located at a certain distance from that point
Here is the geojson sample I will use:
var testJson = {
"type" : "Polygon",
"properties": {},
"geometry" : [
[
[ 40.8003, -73.9580 ],
[ 40.7968, -73.9498 ],
[ 40.7648, -73.9737 ],
[ 40.7681, -73.9814 ],
[ 40.8003, -73.9580 ]
]
]
};
I want to save it into the mongodb database and be able to query it.
For this, I do the following:
I create a mongoose schema:
var GeoSchema = mongoose.Schema({
"type": { "type": String },
"properties": { "type": Object },
"geometry": {
"type": Array,
"index": '2dsphere'
}
});
I create a mongoose model:
var GeoModel = mongoose.model('GeoModel', GeoSchema);
I save the geojson to my database:
var post = new GeoModel(testJson);
post.save(function(err,doc) {
if (err) throw err;
console.log(
"After Save:\n%s", JSON.stringify( doc, undefined, 4 ) );
});
And, finally I search and find the record:
GeoModel.find({
geometry: [
[ 40.8003, -73.9580 ],
[ 40.7968, -73.9498 ],
[ 40.7648, -73.9737 ],
[ 40.7681, -73.9814 ],
[ 40.8003, -73.9580 ]
]
}, function(err, records) {
if (err) return console.log(err);
console.log(records);
});
The issues I need help with:
I will load lots and lots geojson data in the form of polygons.
Lets say I am located at the following coordinates:
40.8003, -73.9580
For a distance of x kilometers, I want to be able all the polygons that are in range.
So, I am thinking of doing a query similar to this, which of course is not working :):
GeoModel.find(
{
geometry: {
$near : {
$geometry : {
type : "Point" ,
coordinates : [40.8003, -73.9580]
},
$maxDistance : 20000
}
},
}, function(err, records) {
if (err) return console.log(err);
console.log(records);
}
);
And I get this error:
{ [MongoError: Unable to execute query: error processing query: ns=coverageMap.geomodels limit=1000 skip=0
Tree: GEONEAR field=geometry maxdist=20000 isNearSphere=0
Sort: {}
Proj: {}
planner returned error: unable to find index for $geoNear query]
name: 'MongoError',
message: 'Unable to execute query: error processing query: ns=coverageMap.geomodels limit=1000 skip=0\nTree: GEONEAR field=geometry maxdist=20000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
'$err': 'Unable to execute query: error processing query: ns=coverageMap.geomodels limit=1000 skip=0\nTree: GEONEAR field=geometry maxdist=20000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
code: 17007 }
Any ideas on how to solve this?
Thank you!

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