How to search in nested objects?

How i can search for the value “20044” in all fields “Barcode” and just in field “Barcode” in a nested object without specifying an absolute path e.g. " Item.Item.Item.Barcode " in MongoDB?

My current solutions:

Search in all text fields, not only in “Barcode” fields

find({$text: {$search: '20044'}})

Search in one specifying absolute path and not in all “Barcode” fields

find({'Item.Item.Item.Barcode': '20044'})

This is my databse object:

{
  "_id": {
    "$oid": "633d7cc238d7f8dafeace6f5"
  },
  "Number": "2",
  "Item": [
    {
      "Type": "FrameElement",
      "Item": [
        {
          "Type": "Frame",
          "Barcode": "20011"
        },
        {
          "Type": "Frame",
          "Barcode": "20012"
        },
        {
          "Type": "SashElement",
          "Item": [
            {
              "Type": "Sash",
              "Barcode": "20021"
            },
            {
              "Type": "Sash",
              "Barcode": "20022"
            },
            {
              "Type": "GlassBarElement",
              "Item": [
                {
                  "Type": "GlassBar",
                  "Barcode": "20031"
                },
                {
                  "Type": "GlassBar",
                  "Barcode": "20032"
                }
              ]
            }
          ]
        },
        {
          "Type": "Glass",
          "Barcode": "20016"
        },
        {
          "Type": "GlassBarElement",
          "Item": [
            {
              "Type": "GlassBar",
              "Barcode": "20043"
            },
            {
              "Type": "GlassBar",
              "Barcode": "20044"
            }
          ]
        }
      ]
    }
  ]
}

Hi @Igor_Lovrinovic , thanks for the question and welcome to the MongoDB community!

You can search over nested objects using Atlas Search. After creating Atlas Search search indexes, you can use $search directly to query nested objects instead of $text.

Once using Atlas Search, you may also consider looking into embeddedDocs or, specifying multiple absolute paths in your search index, ie. Item.Barcode, Item.Item.Barcode, Item.Item.Item.Barcode, etc.

Hope this helps! Please do not hesitate to reply back to this thread if you have more quesitons.

Hello @amyjian , thank you for your answer. The nesting of objects “Item.Item.Item…” can be infinite until “Barcode” comes along. I can’t create absolute paths. I have no idea what this query should look like?

I use:

MongoDB Community Server
6.0.2

MongoDB Compass
Version 1.33.1

Hi @Igor_Lovrinovic , thanks for providing more details. I understand now that you are using MongoDB Community, which is not supported by MongoDB’s full text search solution, Atlas Search.

If you’re interested in addressing your search needs via Atlas Search, you can read more about it here. You can also try it with a free MongoDB Atlas cluster! Sign up here. Hope this helps.