I'm trying to retrieve one specific object from an existing array inside the DB document, using wildcards $near
and $geometry
.
I have a model that looks like this:
const schema = new mongoose.Schema({name: {...},email: {...},...locations: [ { name: String, address: String, mapurl: String, location: { type: { type: String, default: "Point", }, coordinates: [ { type: Number, }, ], }, }, ],}
Schema indexed like that:
schema.index({ "locations.location": "2dsphere" });
Document in DB looks like this:
{"_id": ...,"name": ...,"email": ...,"locations": [ {"name": "name 1","address": "address 1","mapurl": "https://maps.google.com/SOME_MAP_URL_1","location": {"type": "Point","coordinates": [ 11.1111, 12.2222 ] },"_id": {"$oid": "..." } }, {"name": "name 2","address": "address 2","mapurl": "https://maps.google.com/SOME_MAP_URL_2","location": {"type": "Point","coordinates": [ 22.3333, 23.4444 ] },"_id": {"$oid": "..." } }, {"name": "name 3","address": "address 3","mapurl": "https://maps.google.com/SOME_MAP_URL_3","location": {"type": "Point","coordinates": [ 33.4444, 34.5555 ] },"_id": {"$oid": "..." } }, ],}
I'm trying to query DB for a specific Object in an Array and than get all info I need from that Object with .select()
:
const q = { _id: place._id,"locations.location": { $near: { $geometry: { type: "Point", coordinates: [22.333, 23.444] }, $maxDistance: 100, // 100m }, }, }; const storeCoords = await Place.find(q).select("locations.location");
As the result I'm expecting to get only one specific Object from Array that is near 100 meters from provided coordinates, but instead I'm getting the whole Array with all existing Object there, including the one I need.
Expecting result:
{"coords": [ {"_id": "...","locations": [ {"location": {"type": "Point","coordinates": [22.3333, 23.4444] } }, ] } ]}
Actual result:
{"coords": [ {"_id": "...","locations": [ {"location": {"type": "Point","coordinates": [11.1111, 12.2222] } }, {"location": {"type": "Point","coordinates": [22.3333, 23.4444] } }, {"location": {"type": "Point","coordinates": [33.4444, 34.5555] } } ] } ]}
I might use that $near
and $geometry
in a wrong way or completly wrong wildcards.Please, advise.