I've looked at other issues without finding a suitable answer for my problem, so I hope you may help me.
SITUATION
I am currently working on a localisation app with MongoDB
. For the moment I test my queries in the MongoDB
shell.
I have a collection of Point
documents with locations. I use GeoJSON
objects for the coordinates of my point.
Here is what a Point document looks like :
{
_id: "Roma_DellArte",
localisations: [
{ location_type_id: 1, location: { type: "Point", coordinates: [ 41.9097306,12.2558141 ] } }
]
}
My location_type_id
refers to another collection, juste for you to know.
I already made a query which gets me all the points near a precise location :
db.point.createIndex({ 'localisations.location': "2dsphere" })
db.point.find({
'localisations.location': {
$near: {
$geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
$minDistance: 0,
$maxDistance: 100000
}
}
})
Now I would like to query all the points which are near a precise location AND those with a specific location_type_id
.
TRIES AND FAILS
I tried many queries in the MongoDB
shell but none of them produced a satisfying result.
Query 1
I think it doesn't return anything because location:
isn't an exact field.
db.point.createIndex({ location: "2dsphere" })
db.point.find({
'localisations': {
location_type_id: 1,
location: {
$near: {
$geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
$minDistance: 0,
$maxDistance: 100000
}
}
}
})
Query 2
The main problem here is it gets me a point document if in the localisations
field there is an object with a correct location_type_id
and an object with the correct location
. It is not necessarily the same object, which I want it to be.
see: https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#combination-of-elements-satisfies-the-criteria - second paragraph at the end.
db.point.createIndex({ 'localisations.location': "2dsphere" })
db.point.find({
'localisations.location_type_id': 1,
'localisations.location': {
$near: {
$geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
$minDistance: 0,
$maxDistance: 100000
}
}
})
Query 3
I wanted to try this method : https://docs.mongodb.com/manual/tutorial/query-arrays/#query-for-an-array-element-that-meets-multiple-criteria
db.point.createIndex({ location: "2dsphere" })
db.point.find({
localisations: {
$elemMatch: {
location_type_id: 1,
location: {
$near: {
$geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
$minDistance: 0,
$maxDistance: 100000
}
}
}
}
})
Unfortunately, I get this error:
Error: error: {
"ok" : 0,
"errmsg" : "geoNear must be top-level expr",
"code" : 2,
"codeName" : "BadValue"
}
Now you know everything, I hope you can help me.