zeus
zeus

Reputation: 13367

In MongoDB how to use "$expr" with an array?

Let's say I have the below document:

    {
     MyField1: 'A',
     MyArray: [
      {
       MyArrayField1: 'C';
      },
      {
       MyArrayField1: 'A';
      }
     ]
    }

How can I select all documents in MyArray an object with MyArrayField1 = MyField1?

I tried

db.find({$expr: {$eq: ["$MyArray.MyArrayField1", "$MyField1"]}})

even

db.find({$expr: {$eq: ["$MyArray.MyArrayField1", "A"]}})

but it's not working :(

Upvotes: 7

Views: 5586

Answers (1)

mickl
mickl

Reputation: 49945

You can use $in operator

db.col.find({
    $expr: {
        $in: [ "$MyField1", "$MyArray.MyArrayField1" ]
    }
})

In this case MyArray.MyArrayField1 will represent an array of two values A and C

Upvotes: 8

Related Questions