Using javascript variables

Could someone help me with this problem?
I want to find the points closest to a specific point, using the name, instead of the coordinates.
The query would be something like:

var myLocation= db.places.aggregate([
{ $match: { nom: “MongoDB Headquarters” } },
{$project: {_id:0, coord:"$location.coordinates"}}
])

This returns something like:
{ “coord” : [ -73.97, 40.78 ] }

And then to look for the places closest to this one:

db.empreses.aggregate([
{ $geoNear: {
near: { type: “Point”, coordinates: myLocation.coord },
distanceField: “distance”,
minDistance: 1,
num: 1,
}
}
])

Instead of:
db.empreses.aggregate([
{ $geoNear: {
near: { type: “Point”, coordinates: [ -73.97, 40.78 ] },
distanceField: “distance”,
minDistance: 1,
num: 1,
}
}
])

but it doesn’t work

The error message is : “myLocation is not defined”

How could I do this query?

I’ve got it!
I already know how to do it.

var myLocation= db.places.aggregate([
{ $match: { nom: “MongoDB Headquarters” } },
{$project: {_id:0, coord:"$location.coordinates"}}
]).toArray()

db.empreses.aggregate([
{ $geoNear: {
near: { type: “Point”, coordinates: myLocation[0].coord },
distanceField: “distance”,
minDistance: 1,
num: 1 } } ])

1 Like