1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Will it work on aggregation as well?
When I try the opposite - $nin it doesn't work I got an error: uery failed: (InvalidPipelineOperator) Unrecognized expression '$nin'
$expr uses aggregation expressions, which $nin is not. You can achieve the same result by wrapping $in with $not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.