select twitter near a specific coordinates from mongodb - mongodb

I've stored some twitter from streaming api to MongoDB. They are all in jason format and has attribute like below:
"geo" : { "type" : "Point", "coordinates" : [ 42.03759247, -71.82113956 ] }
I'm just wondering what is the correct query to select tweet near a specific coordinates. I did it like this:
db.tweets.find( { coordinates : { $near : [151.1955562233925,-33.87107475181752] , $maxDistance : 1000} } )
but it didn't work. Thank you for your answer!

According to this page, you must first create a geo-spatial index to be able to query geographically:
Now, inorder to query by geo co-ordinates, we need to create an index
over the “loc” field of our dealership documents.
db.dealerships.ensureIndex({loc:"2d"})
So try something like this:
db.tweets.ensureIndex({"coordinates":"2d"})
You might also need to change the structure of your "geo" property to match the following (I'm not sure about this part):
"geo" : { "type" : "Point", "coordinates" : { "lon":42.03759247, "lat":-71.82113956 } }

This works for me:
db.tweets.ensureIndex({"coordinates.coordinates":"2d"})
Query:
db.tweets.find({"coordinates.coordinates": {$near:[-1,-53]}}).limit(2)

Related

GeoLocation query in mongo db

How Could i get longitude and lattitude using mongodb query from mongo collection
based on disatnce and certain coordinates.
{
"_id" : ObjectId("5a559b13ae201d0c05cb6f6a"),
"id" : "99623",
"city" : "Wasilla",
"cnty" : "Matanuska Susitna",
"cntyFips" : null,
"st" : "AK",
"stName" : "Alaska",
"areaCode" : "907",
"lat" : 61.5816,
"long" : -149.4393,
"rgn" : "West",
"__v" : 0
}
in this document "lat" is for latitude and "long" is for longitude.
so basically i have to get all ids based on present id lat and long which comes in a particular miles distance range.
Mongo supports GeoJSON which should allow you to perform basic queries easily on these kind of data. Examples include $geoWithin for your particular use-case.
We need a little more information on the structure of the documents that you are querying, but here is a simple example of the query available in the Mongo documentation here.
It's worth noting that you require a 2dsphere index for location data defined as GeoJSON points in order for this to be effective.
{
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$minDistance: <distance in meters>,
$maxDistance: <distance in meters>
}
}

mongodb geospacial query : $centerSphere not giving good result

I have a db with geodata (lng,lat) from Europe.
I'm trying to do a geospatial query to get all element within a circle.
So, i create a GeoJSON field, and a 2dsphere index on it.
This look like that :
{
"_id" : ObjectId("56c3484612aeb853a83ec336"),
"defaultLabel" : "Zoo de Mulhouse",
"weight" : NumberInt(1),
"country" : "FR",
"loc" : {
"type" : "Point",
"coordinates" : [
47.731673,
7.347819
]
}
}
and db.myCollection.createIndex({"loc":"2dsphere"});
So far, so good.
But then i tried some queries to check.
I took a point at ~1,12 km (1120m) from the data, and did a request with a radius of 1200m.
db.poi.find({loc:
{$geoWithin:
{$centerSphere:[
[47.728593,7.333486],
1200 / 6378100] // radius of earth ~6378.1Km
}
}
})
I got no result.
With the same request, i have to put about 1650m to get the result.
Obviously, this is not acceptable.
So, what did I do wrong?
Found the problem : coordinates were stored as [lat,lgn] in my legacy, and i didn't check before create my GeoJSON, so it was in the wrong order.

spring mongo support for geoJSOn for 2dsphere index

Mongo though provides 2dsphere index on legacy co-ordinates, the query requires to present to Point/Shapes in geoJSON format. For e.g., I have inserted the following records to address collection.
{ "city" : "First", "geo" : [ 13.45, 23.46 ] }
{ "city" : "Second", "geo" : [ 13.45, 20.46 ] }
Then I added 2dsphere index using following command as mongodb still allows 2dsphere index on legacy co-ordinates.
db.address.ensureIndex({"geo":"2dsphere"})
Then if I do $near query using legacy format, but got an exception.
> db.address.find({"geo":{$near:{"x":13.45,"y":23.45}}})
error: {
"$err" : "can't parse query (2dsphere): { $near: { x: 13.45, y: 23.45 } }",
"code" : 16535
}
But If do same query with geoJSON format, then I get result.
> db.address.find({"geo":{$near:{"type":"Point",coordinates:[13.45,23.45]}}})
{ "_id" : ObjectId("537306b4b8ac1f134d9efe89"), "city" : "First", "geo" : [ 13.45, 23.46 ] }
{ "_id" : ObjectId("537306c3b8ac1f134d9efe8a"), "city" : "Second", "geo" : [ 13.45, 20.46 ] }
My question is, GeoConverters has all conversion made to legacy format. So, obviously they wont' work if I use 2dsphere index. Are there any converts available for geoJSON format. Is there any workaround?
Currently spring-data-mongo doesn't support the new mongo (> 2.4) 2dsphere indexes. There is a open issue on Jira about it:
https://jira.spring.io/browse/DATAMONGO-1113?jql=project%20%3D%20DATAMONGO%20AND%20text%20~%20%22%24geometry%22
In the link you can find a gist link to example of how create such converters. You can use it or you can overcome this limitation creating a #Query with the query that you want that spring-data-mongo execute.
Regards.
avaz

Only retrieve back select sub properties and limit how many items they contain

I have a very simple document:
{
"_id" : ObjectId("5347ff73e4b0e4fcbbb7886b"),
"userName" : "ztolley",
"firstName" : "Zac",
"lastName" : "Tolley"
"data" : {
"temperature" : [
{
"celsius" : 22,
"timestamp" : 1212140000
}
]
}
}
I want to find a way to write a query that searches for userName = 'ztolley' and only returns back the last 10 temperature readings. I've been able to say just return the data field but I couldn't find a way to say just return data.temperature (there are many different data properties).
When I tried
db.user.find({userName:'ztolley'},{data: {temperature: {$slice: -10}}})
I got unsupported projection.
I'd try using the Aggregation framework http://docs.mongodb.org/manual/aggregation/ .
Using your schema this should work:
db.user.aggregate([{$match:{"userName":"ztolley"}},{$unwind:"$data.temperature"},{$sort:{"data.temperature.timestamp":-1}},{$limit:10}, {$project:{"data.temperature":1, _id:0}}])
It returns the temperature readings for that user, in reverse sorted order by timestamp, limited to 10.
It looks you write wrong projection, try it with dot '.' notation:
db.user.find( { userName:'ztolley' },{ 'data.temperature': { $slice: -10 } } );

query the value of a sub document in mongodb

I'm using the Java driver withe document that looks like this (a real test example):
{
"_id" : ObjectId("5207fe359b88bfa6f90a82b0"),
"meta_id" : "d6eb1b13-50c7-473f-8348-b5a638a542a0",
"name" : "Fake Name Inc.",
"created" : ISODate("2013-08-11T21:12:21.533Z"),
"members" : {
"5207fe359b88bfa6f90a82af" : [
"Admin",
"User"
]
}
}
I want to select the string array at the path "members.5207fe359b88bfa6f90a82af" (which is a list of roles).
I'm at a loss as to how to do that. It looks like a projection would work here, but I'm new enough to Mongo that the way the projection is written is not obvious.
I can of course load the whole object or maybe even just the "members" field, but I think I should be able to select just exactly the data I'm after.
So, does anyone have an idea of how such a query would be written?
Note: This question suggests that maybe I need to change the structure of the document to make things easier: MongoDB - Query by sub-tree
You can use dot notation in the projection parameter of find to do this. In the shell:
db.test.find(
{_id : ObjectId("5207fe359b88bfa6f90a82b0")},
{'members.5207fe359b88bfa6f90a82af': 1, _id: 0})
Returns:
{
"members": {
"5207fe359b88bfa6f90a82af": [
"Admin",
"User"
]
}
}