3

How can I match a field in MongoDB with value from another field of the same collection.

For example from the collection test: (not exactly the same collection but it serves the need)

test:

{
    "a" : "one",
    "b" : "two",
    "c" : "three"
    "d" : "one"
}

I need to fetch document where value of 'a' matches the value of 'd'. I tried:

db.test.aggregate([
    {$match:{a:'$d'}}
])

but no hope!!!

2
  • You need to use the $expr (and aggregation operators) to match two fields within the document. Commented Nov 23, 2020 at 9:35
  • You can even use the matching in a find method (instead of an aggregation match) when used with expr. Commented Nov 23, 2020 at 9:45

1 Answer 1

3
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          "$a",
          "$d"
        ]
      }
    }
  }
])

Working Mongo playground

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

Comments

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.