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
}
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
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.
Guys I am trying to query all the polygons inside by bounding box but it simply returns 0.. It should be returning many polygons!
Alternatively I try to query a much larger bounding box and nothing happens!
My query is:
{
geometry:
{ $geoWithin:
{ $box:
[ [-73.995762,40.764826], [-73.934034,40.802038] ]
}
}
}
Notice that the very same query returns a valid result for geometries of type Point
to query all the polygons inside by bounding box but it simply returns 0
The $box operator for $geoWithin only supports documents based on grid coordinates and does not support GeoJSON shapes format.
the very same query returns a valid result for geometries of type Point
Depending on your documents structure, and how you are querying them, this is probably treated as being grid coordinates i.e. {geometry: [<long>, <lat>]}
This may not have worked for your polygons document because GeoJSON Polygons require an extra array wrapper. i.e. [[ [<long>, <lat>] ]] invalidating the grid coordinates format.
If your documents are in GeoJSON format, and you would like to select an area, you could utilise $geometry instead.
db.places.find(
{
'geometry': {
$geoWithin: {
$geometry: {
type : "Polygon" ,
coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] ]
}
}
}
}
)
Worth noting that MongoDB Compass geospatial visualisation currently (v1.6) does not support GeoJSON yet.
Here goes the answer:
$box do work with GeoJSON, but not with polygons! You need to generate a geometry with the $box instead.
Also, it always has to has the start point and point, so a 4-point polygon will have 5 coordinate tuples
BUT it gets trickier, it has to follow the right hand rule (anticlockwise).
TESTING GEOJSON WITH $BOX AND POINTS
my query:
{
geometry: {
$geoWithin: {
$box: [
[ -71.934034, 38.764826 ],
[ -75.995762, 43.802038 ]
]
}
}
}
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'm trying to build a near query with additional condition:
query = {
$and : [
{ address : { $near : [x, y] } },
{ available: 1 }
]
};
db.points.find(query)
It gives me an error:
error: {
"$err" : "can't find any special indices: 2d (needs index), 2dsphere (needs index), for: { $and: [ { ipaddr: { $near: [ -82.49412043543862, 0.0 ] } }, { available: 1.0 } ] }",
"code" : 13038
}
Otherwise, the query like this works fine
query = { address : { $near : [x, y] }, available : 1 }
I need to use $and to build complex query.
Can I build $near query with $and keyword?
see this topic - https://jira.mongodb.org/browse/SERVER-4572 - looks like it's a bug and it's not fixed yet..
Probably not the greatest solution but I found a way to work around this issue. What I did is split the query into 2 parts 1) query the nearest addresses and get the objects ids 2) use it in the second query using $in operator.