Home > Net >  MongoDB - How to match the value of a field with nested document field value
MongoDB - How to match the value of a field with nested document field value

Time:08-24

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.

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?

CodePudding user response:

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

  • Related