Home > Enterprise >  MongoDB find if property in array of objects equals to another field
MongoDB find if property in array of objects equals to another field

Time:01-15

This is the document model:

{
  foo: {
    bar: 1
  },
  some_array: [
    {
      xyz: 1
    },
    {
      xyz: 2
    }
  ]
},

{
  foo: {
    bar: 2
  },
  some_array: [
    {
      xyz: 123
    },
    {
      xyz: 321
    }
  ]
}

I want to find the documents that 'foo.bar' equals to 'some_array.xyz'.

As the example, only the first document should be fetched.

How to do it?

CodePudding user response:

You can use the $expr operator to compare fields within the same document.

db.collection.find({
  $expr: {
    $in: [
      "$foo.bar",
      "$some_array.xyz"
    ]
  }
})

Working MongoPlayground

  •  Tags:  
  • Related