Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB – How to match the value of a field with nested document field value

I have a structure where I want to match the value of a field on root level with the value of a field inside another object in the same document, I got to his structure by unwinding on the nested field. So I have a structure like this:

{
   "name": "somename",
   "level": "123",
   "nested":[ 
        {
          "somefield": "test",
          "file": {
             level:"123"
          }
     },
     {
         "somefield": "test2",
         "file": {
            level:"124"
        }
     }
  ]
}

After unwinding I got the structure like:

{
   "name": "somename",
   "level": "123",
   "nested": {
      "somefield": "test",
      "file": {
         level:"123"
       }
    }
}

So I want to match on level = nested.file.level and return only documents which satisfy this condition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried using

$match: {
    "nested.file.level": '$level'
}

also

$project: {
    nested: {
        $cond: [{
                $eq: [
                    'nested.file.level',
                    '$level'
                ]
            },
            '$nested',
            null
        ]
    }
}

Nothing seems to work. Any idea on how I can match based on the mentioned criteria?

>Solution :

Solution 1: With $unwind stage

After $unwind stage, in the $match stage you need to use the $expr operator.

{
  $match: {
    $expr: {
      $eq: [
        "$nested.file.level",
        "$level"
      ]
    }
  }
}

Demo Solution 1 @ Mongo Playground


Solution 2: Without $unwind stage

Without $unwind stage, you may work with $filter operator.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $in: [
          "$level",
          "$nested.file.level"
        ]
      }
    }
  },
  {
    $project: {
      nested: {
        $filter: {
          input: "$nested",
          cond: {
            $eq: [
              "$$this.file.level",
              "$level"
            ]
          }
        }
      }
    }
  }
])

Demo Solution 2 @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading