DimaA6_ABC
DimaA6_ABC

Reputation: 622

MongoDB - filter by several array elements

Suppose I have documents like this:

{
    "_id", "1",
    "myarray": [
        {
           "address": "abc",
           "role": "input",
        }
        {
           "address": "def",
           "role": "output",
        }
    ]
},
{
    "_id", "2",
    "myarray": [
        {
           "address": "xyz",
           "role": "input",
        }
        {
           "address": "abc",
           "role": "output",
        }
    ]
}

I want to return documents where myarray.address is abc and myarray.role is output, but not the documents where exists myarray.address='abc' and exists myarray.role='output', but the documents where exists element of myarray array:

address: "abc",
role: "output"

Using the example above, I want only the document with _id=2.

Upvotes: 2

Views: 63

Answers (1)

Ashh
Ashh

Reputation: 46481

You can use $elemMatch query operator to match multiple fields inside an array

db.collection.find({ myArray: { $elemMatch: { address: 'abc', role: 'output' }}})

Upvotes: 2

Related Questions