How to query the "car" collection, which stores a document for every car, and retrieve all cars that include specific keywords in their names. Then, find the latest "carInfo" document for each of these cars and return only the cars that are within a certain distance (X miles) from given coordinates.
Here are the schemas for the relevant collections:
Car Schema:
{
"_id": "ObjectId",
"name": "String",
}
CarInfo Schema:
{
"car": {
"$ref": "Car"
},
"address": {
"location": {
"type": "Point",
"coordinates": [Number]
}
},
"timestamp": "Date",
}
I tried this but I keep getting:
MongoServerError: $geoNear, $near, and $nearSphere are not allowed in this context
db.cars.aggregate([
{
$match: {
name: { $in: KEYWORDS},
},
},
{
$lookup: {
from: 'carinfos',
localField: '_id',
foreignField: 'car',
as: 'carInfo',
pipeline: [{ $sort: { timestamp: -1 } }, { $limit: 1 }],
},
},
{
$unwind: '$carInfo',
},
{
$match: {
'carInfo.address.location': {
$near: {
$geometry: {
type: 'Point',
coordinates: coordinates,
},
$maxDistance: 5 * 1609.34,
},
},
},
}
])
2
Answers
One option is to do something like this:
carinfos
which where in range during the last weekcar
dataKEYWORDS
See how it works on the playground example without the
$near
step as it is not supported