How to use aggregation in MongoDB Atlas to search keyword/string present in object inside another object

how to use atlas search to search a keyword present in my ‘company’ key which is an object

{
  name:"abcd",
  price:"21",
  text:"aaa",
  comapny:{
          name:"bbbb"
          }
 }
`

Hi @Adhil_E and welcome to MongoDB the community forum!!

Based on the sample data provided above, I created the index in the following way:

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "company.name": {
        "type": "string"
      }
    }
  }
}

and the following search query returned me the above documents:

db.newAtlasS.aggregate(db.newAtlasS.aggregate([
  {
    $search: {
      index: 'default',
      text: {
        query: 'bbbb',
        path: 'company.name'
      }
    }
  }
]
)

Output for which is:

[
  {
    _id: ObjectId("63864d60959925ab51e0cf96"),
    name: 'abcd',
    price: '21',
    test: 'aaa',
    company: { name: 'bbbb' }
  }
]

For more detailed information, please refer to the documentation on nested field search.

Let us know if you have any further queries.

Best Regards
Aasawari

This topic was automatically closed after 180 days. New replies are no longer allowed.