How to search referenced document

I have User schema under it I have a referenced Products. How can I apply atlas search to the reference schema under the user.

Hi @Aaron_Parducho,

Are the User and Products seperate collections in the same database? If so, have you tried using $lookup stage after the $search stage in your pipeline? An example of $lookup usage below where the Users and Products collections are in the same database.

Document inside of the Users collection:

  {
    _id: ObjectId("61b9689290d396c8ef8d4e6f"),
    name: 'TestUser1',
    product_purchased: 'water'
  }

Document inside of the Products collection:

  {
    _id: ObjectId("61b969e090d396c8ef8d4e71"),
    product_id: 12345,
    product_name: 'water',
    brand: 'general brand',
    product_volume: '600mL'
  }

Using the $lookup stage:

[primary] searchdb> lookupStage = {
  '$lookup': {
    from: 'Products',
    localField: 'product_purchased',
    foreignField: 'product_name',
    as: 'product_details'
  }
}

[primary] searchdb> db.Users.aggregate([lookupStage])
[
  {
    _id: ObjectId("61b9689290d396c8ef8d4e6f"),
    name: 'TestUser1',
    product_purchased: 'water',
    product_details: [
      {
        _id: ObjectId("61b969e090d396c8ef8d4e71"),
        product_id: 12345,
        product_name: 'water',
        brand: 'general brand',
        product_volume: '600mL'
      }
    ]
  }
]

Hope this helps. If you require further assistance, please provide:

  1. Sample document(s) based on the User schema
  2. Sample document(s) based on the Products schema
  3. The search query you’re currently running
  4. The desired output document(s)

Best Regards,
Jason

Thanks @Jason_Tran can you guide me using the lookup after the $search. What it should look like with atlas search.

Hi @Aaron_Parducho,

You can add it as a later stage after your $search stage.

For example:
creating the $search stage of the pipeline to return a set of document(s)

[primary] searchdb> stage1= { '$search': { index: 'default', text: { query: 'TestUser1', path: 'name' } }}

using the $search stage (stage1) followed by the $lookup stage (lookupStage)

[primary] searchdb> db.Users.aggregate([stage1,lookupStage])
[
  {
    _id: ObjectId("61b9689290d396c8ef8d4e6f"),
    name: 'TestUser1',
    product_purchased: 'water',
    product_details: [
      {
        _id: ObjectId("61b969e090d396c8ef8d4e71"),
        product_id: 12345,
        product_name: 'water',
        brand: 'general brand',
        product_volume: '600mL'
      }
    ]
  }
]

You may wish to review the aggregation pipeline and $lookup documentation.

Hopefully this helps.

Regards,
Jason

1 Like