Hi @Suray_T,
I understand how to implement these steps using separate pipelines/queries, but I am hoping to complete both of these steps in one trip to the database.
My goal involves two steps:
- Find stores within a certain radius of the user (I use $geoNear for this)
- Find all of the products in these “nearby” stores
Have you attempted using $geoNear
with a $lookup
in a pipeline?
What are some possible approaches?
I have a simple example below which uses data from my test environment below which uses the $lookup
stage after $geoNear
. You may need to alter this accordingly and test thoroughly to determine if it suits your use case / requirements:
db.stores.aggregate([
{
'$geoNear': {
near: { type: 'Point', coordinates: [ -87.05, 42.67 ] },
distanceField: 'distance'
}
},
{
'$lookup': {
from: 'products',
localField: 'number',
foreignField: 'storeNumber',
as: 'storeItems'
}
}
])
Output:
[
{
_id: ObjectId("62f9d1fbab5d901302a457e4"),
name: 'Store A',
number: 345,
location: { type: 'Point', coordinates: [ -87.05365159, 42.67955354 ] },
distance: 1104.6830501177644,
storeItems: [
{
_id: ObjectId("62f9d1afab5d901302a457e1"),
name: 'Table',
storeNumber: 345
},
{
_id: ObjectId("62f9d1b5ab5d901302a457e2"),
name: 'Chair',
storeNumber: 345
},
{
_id: ObjectId("62f9d1c5ab5d901302a457e3"),
name: 'Cushions',
storeNumber: 345
}
]
}
]
If this is not what you are after or are still having troubles, please advise:
- MongoDB version in use
- What you have attempted so far
- Expected output document(s)
Regards,
Jason