Use property for calculation in mongodb - mongodb

specialists,
I have a document with several properties, one bein an lon/lat-array with a 2d index on it.
Another property is a radius property.
What I want:
{
geo:{
$within: { $center: [[ 9.078597000000036,50.580947], 1+radius]}
}
}
Is this available with mongodb? No matter what I am searching in google I am always directed to the mongodb documentation about geospatial indexes but my question is not getting answered.

Not sure if i understand you, but the docs page about geospatial indexes give a an example of a query like yours:
db.places.find( { geo: { $centerSphere: [ [long,lat ] ,
radius ] } } )
searches places collection for everything withing radius distance (in radians) from the point [long, lat].

Related

How to optimize a mongodb geospatial query?

A while ago I build the website crowdfundstats.com during a hackathon. The website gives some interesting insides based on the 130.000 or so kickstarter project data that we have scraped. The most interesting feature is the http://crowdfundstats.com/map.html on which you can drag a radius on the worldmap to get information on projects within that radius.
I use the aggregate function to find all projects within the radius based on their geospatial information. Each project has a geo location in the following format:
{ g1 :
{ type : "Point" },
{ coordinates : [ -83.102840423584, 42.354639053345] }
}
The aggregate function then returns the total amount of backers, the average duration, the success percentage and the total amount of projects within the radius:
{'$match' :
{g1 :
{$geoWithin :
{ $centerSphere :[[parseFloat(long), parseFloat(lat) ], radius/6371 ]
}
}
}
},
{'$group':
{ "_id":"",
"backers": {"$sum": "$backers"},
"dateDiff2": {"$avg": "$dateDiff2"},
"completed": {"$avg": "$completed"},
"total": {"$sum": 1}
}
}
The issue is that the result of the query takes a long time (for example: more than 10 seconds when dragging the radius over the UK ). I have already added an 2dsphere index to increase speed, but this has almost no effect:
{
"g1" : "2dsphere"
}
Is there anything I can do to optimise the query, or is this the expected performance on geospatial queries?
Thanks in advance
For anyone stumbling on this thread, I have improved the most heavy query from 15 seconds to 0.5seconds by upgrading from MongoDB 3.0 to 3.2. They have improved geospatial querying immensely. you can read more about it on the MongoDB blog

Filter Documents by Distance Stored in Document with $near

I am using the following example to better explain my need.
I have a set of points(users) on a map and collection schema is as below
{
location:{
latlong:[long,lat]
},
maxDistance:Number
}
i have another collection with events happening in the area. schema is given below
{
eventLocation:{
latlong:[long,lat]
}
}
now users can add their location and the maximum distance they want to travel for to attend an event and save it.
whenever a new event is posted , all the users satisfying their preferences will get a notification. Now how do i query that. i tried following query on user schema
{
$where: {
'location.latlong': {
$near: {
$geometry: {
type: "Point",
coordinates: [long,lat]
},
$maxDistance: this.distance
}
}
}
}
got an error
error: {
"$err" : "Can't canonicalize query: BadValue $where got bad type",
"code" : 17287
}
how do i query the above case as maxDistance is defined by user and is not fixed. i am using 2dsphere index.
Presuming you have already worked out to act on the event data as you recieve it and have it in hand ( if you have not, then that is another question, but look at tailable cursors ), then you should have an object with that data for which to query the users with.
This is therefore not a case for JavaScript evaluation with $where, as it cannot access the query data returned from a $near operation anyway. What you want instead is $geoNear from the aggregation framework. This can project the "distance" found from the query, and allow a later stage to "filter" the results against the user stored value for the maximum distance they want to travel to published events:
// Represent retrieved event data
var eventData = {
eventLocation: {
latlong: [long,lat]
}
};
// Find users near that event within their stored distance
User.aggregate(
[
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": eventData.eventLocation.latlong
},
"distanceField": "eventDistance",
"limit": 100000,
"spherical": true
}},
{ "$redact": {
"$cond": {
"if": { "$lt": [ "$eventDistance", "$maxDistance" ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
]
function(err,results) {
// Work with results in here
}
)
Now you do need to be careful with the returned number, as since you appear to be storing in "legacy coordinate pairs" instead of GeoJSON, then the distance returned from this operation will be in radians and not a standard distance. So presuming you are storing in "miles" or "kilometers" on the user objects then you need to calculate via the formula mentioned in the manual under "Calculate Distances Using Spherical Geometry" as mentioned in the manual.
The basics are that you need to divide by the equatorial radius of the earth, being either 3,963.2 miles or 6,378.1 kilometers to convert for a comparison to what you have stored.
The alternate is to store in GeoJSON instead, where there is a consistent measurement in meters.
Assuming "kilometers" that "if" line becomes:
"if": { "$lt": [
"$eventDistance",
{ "$divide": [ "$maxDistance", 6,378.1 ] }
]},
To reliably compare your stored kilometer value to the radian result retured.
The other thing to be aware of is that $geoNear has a default "limit" of 100 results, so you need to "pump up" the "limit" argument there to the number for expected users to possibly match. You might even want to do this in "range lists" of user id's for a really large system, but you can go as big as memory allows within a single aggreation operation and possibly add allowDiskUse where needed.
If you don't tune that parameter, then only the nearest 100 results ( default ) will be returned, which may well no even suit your next operation of filtering those "near" the event to start with. Use common sense though, as you surely have a max distance to even filter out potential users, and that can be added to the query as well.
As stated, the point here is returning the distance for comparison, so the next stage is the $redact operation which can fiter the user's own "travel distance" value against the returned distance from the event. The end result gives only those users that fall within their own distance contraint from the event who will qualify for notification.
That's the logic. You project the distance from the user to the event and then compare to the user stored value for what distance they are prepared to travel. No JavaScript, and all native operators that make it quite fast.
Also as noted in the options and the general commentary, I really do suggest you use a "2dsphere" index for accurate spherical distance calculation as well as converting to GeoJSON storage for your coordinate storage in your database Objects, as they are both general standards that produce consistent results.
Try it without embedding your query in $where: {. The $where operator is for passing a javascript function to the database, which you don't seem to want to do here (and is in fact something you should generally avoid for performance and security reasons). It has nothing to do with location.
{
'location.latlong': {
$near: {
$geometry: {
type: "Point",
coordinates: [long,lat]
},
$maxDistance: this.distance
}
}
}

Mongodb Point inside a Polygon not getting results - Mongoid + Rails

I'm trying to check if a point is inside a polygon with mongodb (mongodb 2.6).
I'm inserting the data in de collection like this:
db.areas.insert({"polygons":
{"type":"Polygon",
coordinates:
[[[-23.0651232, -45.6374645],
[-23.0557255, -45.6435585],
[-23.0370072, -45.6383228],
[-23.0299772, -45.6351471],
[-23.0025649, -45.6480217],
[-22.9723022, -45.6554031],
[-22.9340493, -45.6032181],
[-22.9353140, -45.5925751],
[-22.9383177, -45.5855370],
[-22.9601320, -45.5560112],
[-22.9645577, -45.5597878],
[-22.9938740, -45.5675125],
[-22.9939530, -45.5690575],
[-23.0217620, -45.5712891],
[-23.0241319, -45.5719757],
[-23.0258697, -45.5711174],
[-23.0268966, -45.5721474],
[-23.0656365, -45.6372499],
[-23.0651232, -45.6374645]
]]
}
});
And querying like this:
db.areas.find({polygons:
{$geoIntersects:
{$geometry:{ "type" : "Point",
"coordinates" : [ -22.112, -45.56 ] }
}
}
});
But I'm getting no result. Any ideas?
I've looked this links:
mongodb check if point is in polygon
Search all polygons that contains a series of points in mongodb
Any help will be appreciated
I found the answer.
The problemas was that when I tried to save, the coordinates of the Polygon from a Rails form it was saved as String and not as Double.
I chaged that before save an the problem was solved.

mongodb and geospatial schema

im breaking my head with mongo and geospatial,
so maybe someone has some idea or solution how to solve this:
my object schema is like this sample for geoJSON taken from http://geojson.org/geojson-spec.html.
{
"name":"name",
"geoJSON":{
"type":"FeatureCollection",
"features":[
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[100,0],[101,0],[101,1],[100,1],[100,0]]]},"properties":{}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[100,0],[101,0],[101,1],[100,1],[100,0]]]},"properties":{}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[100,0],[101,0],[101,1],[100,1],[100,0]]]},"properties":{}}
]}}
additional info: I'm using spring data but that shouldn't influence the answer.
main problem is how/where to put indexes in this schema. I need to make a query to find all documents for given Point if some polygon intersects.
thanks in advance.
By creating a 2d or 2dsphere index on geoJSON.features.geometry you should be able to create an index covering all of the geoJSON-objects.
To get all documents where at least one of the sub-object in the features array covers a certain point, you can use the $geoIntersects operator with a geoJSON Point:
db.yourcollection.find(
{ `geoJSON.features.geometry` :
{ $geoIntersects :
{ $geometry :
{ type : "Point" ,
coordinates: [ 100.5 , 0.5 ]
}
}
}
}
)

how to deal with complicated query in mongodb?

I use mongodb to save the temporal and spatial data, and the document item is structured as follows:
doc = { time:t,
geo:[x,y]
}
If the different of two docs are defined as:
dist(doc1, doc2) = |t1-t2| + |x1-x2| + |y1 - y2|
How can I query the documents by mongodb and sort the results by their distance to a given document doc0 ={ time:t0, geo:[x0,y0] }?
thanks
Instead of calculating the distance manually, you could trust mongodb with that task. Mongodb has built in geospatial query support.
This would look like this:
db.docs.find( {
"time": "t0",
"geo" : { $near : [x0,y0] }
} ).limit(20)
The result would be all documents near the given location [x0,y0], automatically ordered by distance to that point.