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.
Related
The $nearSphere MongoDB operator is able to return the documents near to a given point (specified as parameter of the operator) sorted by incresing distance.
However, how to get the actual distance? Is there any mean of getting this using MongoDB functionality? Either with $nearSphere (although I have checked its documentation and I haven't found this information) or with other mechanisms (maybe the aggregation framework?)
Thanks!
With aggregation you can use the $geoNear stage to provide both spherical geometry and return the distance.
Example from the docs:
db.places.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
distanceField: "dist.calculated",
maxDistance: 2,
query: { category: "Parks" },
includeLocs: "dist.location",
spherical: true
}
}
])
I have a location collection, and have used this code that shows location near the assigned geo location below:
db.location.find({ll:{$near:[-80.12996, 25.79315]}}).limit(5).pretty()
However, now I need to expand from this and find the top 5 pizza restaurant (field is type: "Pizza"), and ordered by the geo location above (need to use near to have it by ascending). Can't figure out how to do it. I tried to use aggregate but not working for me, I might have it in the wrong order or something.
step 1: create an index of the field with have location.
db.location.createIndex( { <location field> : "2dsphere" } )
step 2: try this query replacing your coordinates in lat lng:
db.location.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [lat, lng]},
maxDistance:1000,
distanceField: "dist.calculated",
spherical: true
}
},
{
$match: {
type: "Pizza",
}
},
{
$sort: {
'dist.calculated': 1
}
},
{
$limit : 5
}
])
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 ] },
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.