Querying with results from $geoNear

Say I have two collections: “stores” and “products”.

Example store document:

{
  "_id": {
    "$oid": "61416551dc536c566dd17cb0"
  },
  "name": "Store A",
  "number": 345,
  "location": {
    "type": "Point",
    "coordinates": [
      -87.05365159,
      42.67955354
    ]
  }
}

Example product document

{
  "_id": {
    "$oid": "61416551dc536c566dd17cb1"
  },
  "name": "Table",
  "storeNumber": 345
}

My goal involves two steps:

  1. Find stores within a certain radius of the user (I use $geoNear for this)
  2. Find all of the products in these “nearby” stores

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.

What are some possible approaches?

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:

  1. Find stores within a certain radius of the user (I use $geoNear for this)
  2. 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:

  1. MongoDB version in use
  2. What you have attempted so far
  3. Expected output document(s)

Regards,
Jason

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.