skip to Main Content

there is a nested mongodb document that looks like the image below. I want to do a search in the body field in this document, but I could not succeed. how can i do this search. thanks in advance

Image of my document

I tried to search like this. Is my path correct?

const result = await this.campaignModel.find({
       "sequencesPageData": {
         "$elemMatch": {
           "mailSteps": {
             "$elemMatch": {
               "mailTemplate": x
             }
           }
         }
       }
     });

I did a search like this but got no results.

const result = await this.campaignModel.find({
       "sequencesPageData": {
         "$elemMatch": {
           "mailSteps": {
             "$elemMatch": {
               "mailTemplate": x
             }
           }
         }
       }
     });

2

Answers


  1. For object fields, simply access them using dot notation. For array fields, use $elemMatch to perform the match.

    db.collection.find({
      "sequencesPageData.mailSteps": {
        "$elemMatch": {
          "mailTemplate": {
            "$elemMatch": {
              "subject": "asdf"
            }
          }
        }
      }
    })
    

    Mongo Playground

    Login or Signup to reply.
  2. If you are only testing a single field in the array, there is no need to use $elemMatch, you can use dot notation:

    db.collection.find({ "sequencesPageData.mailSteps.mailTemplate.body": "x" })
    

    $elemMatch is useful to ensure that 2 or more tests are satisfied by the same array element, but since this example uses only 1 test, it works without.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search