$geoWithin not returning anything - mongodb

I'm trying to use $geoWithin and $centerSpehere to return a list of items within a radius, but no luck.
This is my item's schema:
var ItemSchema = new Schema({
type : String,
coordinates : []
});
ItemSchema.index({coordinates: '2dsphere'});
This is my database item that I should be seeing:
{
"_id": {
"$oid": "552fae4c13f82d0000000002"
},
"type": "Point",
"coordinates": [
6.7786656,
51.2116958
],
"__v": 0
}
This is running on the server currently just to test, the coordinates seen here will eventually be variable.
Item.find( {
coordinates: { $geoWithin: { $centerSphere: [ [ 51, 6 ], 100/6378.1 ] } }
}, function(err, items) {
console.log(items); // undefined
});
Items are always undefined, even though that coordinate is within 100Km from the other coordinate.
I get no errors in the console.
Any ideas of what's happening? Is the schema wrong?
Thanks.

The format's wrong. The GeoJSON needs to live under one field:
{
"location" : {
"type": "Point",
"coordinates": [6.7786656, 51.2116958]
}
}
See e.g. create a 2dsphere index.

Related

use geonear with fuzzy search text mongodb

I have the following query
db.hotels.aggregate([
{
$search: {
index:'txtIdx', // this is the index name
text: {
query:"sun",
path:['name','address.landmark','address.city','address.state','address.country'],
fuzzy: {
maxEdits:2,
prefixLength: 1,
},
},
},
},
{
$project: {
_id: 1,
name: 1,
address:1,
score: { $meta: "searchScore" }
}
},
{$limit:100},
])
there is also a field called 'location' in hotels' collection, which has coordinates as follows
"location": {
"type": "Point",
"coordinates": [
72.867804,
19.076033
]
}
how can I use geonear with this search query to only return near by hotels from user, with provided latitude, longitude and distance.
I also tried this query
{
$search: {
index:'searchIndex',
compound: {
must: {
text: {
query:'sun',
path:['name','address.landmark','address.city','address.state','address.country'],
fuzzy: {
maxEdits:2,
prefixLength: 3,
},
},
},
should: {
near:{
origin: {
type: 'Point',
coordinates: [-122.45665489904827,37.75118012951178],
},
pivot: 1000,
path: 'location'
},
}
}
}
},
but above query returns results which are not even around that location. It returns same result as 'search' would provide without 'near'.I have created 'geo' index for location, still it doesn't return nearby hotels.
Or is there another way apart from using geonear along with search? I am trying since past 2 days now, and I haven't found anything useful. Also I want to use fuzzy text search only. Please let me know if there is a way to solve this?

Azure CosmosDb MongoAPI nearSphere return nothing

I'm using CosmosDB with MongoDb API and I'd like to use $nearSphere to find Documents.
Here is the exemple of one document I have in my collection "locations":
{
"_id": {
"$oid": "60523b3dd72e4d4aa21f473b"
},
"data": [{
"Indicateur": "pr50mm",
"Value": 0,
"score": 0,
"Exposure": "low"
}],
"Domain": "EU-CORDEX",
"GCMS": "ICHEC-EC-EARTH",
"RCMS": "RACMO22E",
"Scenario": "rcp85",
"Horizon": "Medium (1941-1970)",
"location": {
"type": "Point",
"coordinates": [26.32, 27.25]
}
}
I would like to find the Document with location the nearest from [26, 27].
When I execute the following request, it returns nothing. However, this same command works fine we a MongoDB database : It returns the documents order by distance with point with coordonates [26, 27].
db.locations.find({
'location': {
$nearSphere: {
$geometry: {
type: 'Point',
coordinates: [
26, 27
]
}
}
}
})
Do you know how I can make it work for Azure CosmosDB?
Thank you in advance.
It looks like for Azure CosmosDB I have to specify location.coordinates in my query. Here is the working query:
db.locations.find({
'location.coordinates': {
$nearSphere: {
$geometry: {
type: 'Point',
coordinates: [
26, 27
]
}
}
}
})
This exemple about $nearSphere helped me: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/cosmos-db/mongodb-feature-support.md
I hope this will help other people!

Mongoose aggregate match returns empty array

I'm working with mongodb aggregations using mongoose and a I'm doubt what am I doing wrong in my application.
Here is my document:
{
"_id": "5bf6fe505ca52c2088c39a45",
"loc": {
"type": "Point",
"coordinates": [
-43.......,
-19......
]
},
"name": "......",
"friendlyName": "....",
"responsibleName": "....",
"countryIdentification": "0000000000",
"categories": [
"5bf43af0f9b41a21e03ef1f9"
]
"created_at": "2018-11-22T19:06:56.912Z",
"__v": 0
}
At the context of my application I need to search documents by GeoJSON, and I execute this search using geoNear. Ok it works fine! But moreover I need to "match" or "filter" specific "categories" in the document. I think it's possible using $match but certainly I'm doing the things wrong. Here is the code:
CompanyModel.aggregate(
[
{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [pageOptions.loc.lng, pageOptions.loc.lat]
},
"distanceField": "distance",
"spherical": true,
"maxDistance": pageOptions.distance
}
},
{
"$match": {
categories: { "$in": [pageOptions.category] }
}
}
]
).then(data => {
resolve({ statusCode: 200, data: data });
}).catch(err => {
console.log(err);
reject({ statusCode: 500, error: "Error getting documents", err: err });
})
pageOptions:
var pageOptions = {
loc: {
lat: parseFloat(req.query.lat),
lng: parseFloat(req.query.lng)
},
distance: parseInt(req.query.distance) || 10000,
category: req.params.category || ""
}
If I remove $match I get all the documents by location, but I need to filter specific categories... I don't believe that I need to filter it manually, I believe it can be possible with aggregation functions...
So anyone can help me with this mongoose implementation?
Thanks for all help
In MongoDB you need to make sure that data type in your document matches the type in your query. In this case you have a string stored in the database and you're trying to use ObjectId to build the $match stage. To fix that you can use valueOf() operator on pageOptions.category, try:
{
"$match": {
categories: { "$in": [pageOptions.category.valueOf()] }
}
}

Find $nearSphere result with zero distance from queried point

I have the following record in my mongoDb:
{
"_id" : ObjectId("56e63313059484f212a4305f"),
"title" : "The video title",
"location" : {
"coordinates" : [
-73.9667,
40.78
],
"type" : "Point"
},
}
I want to be able to find all the points at that exact location.
If I write:
db.videos.find({
location: {
'$nearSphere': {
'$geometry': {
type: 'Point',
coordinates: [-73.9667, 40.78]
},
'$maxDistance': 0
}
}
})[0]
I don't get any results. If I type:
db.videos.find({
location: {
'$nearSphere': {
'$geometry': {
type: 'Point',
coordinates: [-73.9667, 40.78]
},
'$maxDistance': 0.00001
}
}
})[0]
I get the one result.
I looked and looked, and nowhere in the docs say that maxDistance cannot be 0.
Can it?
So as would make sense, $maxDistance set to 0 would be ignored just as if you had not set the option.
If you are looking for an "exact match" then just ask for that. It's not a $nearSphere query by any description:
db.videos.find({
"location.coordinates" : [ -73.9667, 40.78 ]
})
Which will of course return the document matching that "exact" location.
For something a little more complex, then use aggregation $geoNear instead. It projects a "distance" which you can use in later filtering:
db.videos.aggregate([
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [ -73.9667, 40.78 ]
},
"distanceField": "distance",
"spherical": true
}},
{ "$match": { "distance": 0 } }
])
So the intial pipeline stage returns a "distance" and the second stage filters out any results where that distance was in fact 0.
You really only should need that if your queried objects were something like a "Polygon" or other GeoJSON form that would not match the "exact" coordinates array.
The general "exact" array match should suit for "Point" data.

Get only closest documents using mongodb geoNear or near

I'm getting crazy to return closest Venues from a specific point using MongoDB. It is the first time I work on it so I'm totally new to this practice.
What I did at the beginning is to create a 2DIndex of my Venue collection.
Now I'm trying to get Venues in a range of 500 meters from a specific point and the code is this:
Venue.find({ location:
{
$near: [ 52.3835443 , 4.8353073 ],
$maxDistance: 0.5 / 6371
}
}, function (err, venues) {
return venues;
});
Unfortunately it return all documents.
The Venue Model has the field for location like this:
"location": {
"type": {
"type": "string"
},
"coordinates": [{ "type": "Number" }]
}
And all my Venues are like this:
{
"name": "name",
"address": "address",
"location": {
"type": "Point",
"coordinates": [50.1981668, 7.9943994999]
}
}
I also tried using $geoNear but I always receive all documents and not only those in 500 meters distance.
EDIT:
Mongo version is 3.2;
index:
{
"v": 1,
"key": {
"location": "2dsphere"
},
"name": "location_2dsphere",
"ns": "mydb.Venue",
"2dsphereIndexVersion": 2
}
document as wrote above:
{
"name": "A name",
"address": "An address",
"location": {
"type": "Point",
"coordinates": [50.1981668, 7.9943994999]
}
}
The $maxDistance operator constrains the results of a geospatial $near or $nearSphere query to the specified distance. The measuring units for the maximum distance are determined by the coordinate system in use. For GeoJSON point object, specify the distance in meters, not radians. ref here
When I was executing this query I got:
planner returned error: unable to find index for $geoNear query
so added **$geometry ** into query body
Venue.find({ location:
{
$near: {
$geometry : {
type : "Point" ,
coordinates : [ 52.3835443 , 4.8353073 ]},
$maxDistance : 500}}}
}, function (err, venues) {
return venues;
});