0

I was wondering what I'm doing wrong here. I'm trying to query an array of objects. I'm expecting to get the document below, but I'm getting nothing instead.

This is the collection:

[
    {
        _id: ObjectId("5ef1714fc77dd22599054c8d")
        "surveyName": 'Sample',
        "participants": [
            {
                "name": 'John'
                "answers": {
                    'question1': 'abc',
                    'question2': 'def'
                }
            },
            {
                "name": 'Paul'
                "answers": {
                    'question1': 'def',
                    'question2': 'abc'
                }
            }
        ]
    }
]

This is the query I'm trying to run:

db.surveys.find({
    _id: ObjectId("5ef1714fc77dd22599054c8d"),
    'participants.answers': { 
        '$elemMatch': { 
            '$or': [ 
                {'question1': 'abc'},
                {'question2': 'def'}
            ]
        }
    }
})

Result:

Fetched 0 record(s) in 22ms

Thanks!

2
  • 1
    you have two question1 in OR condition. Commented Jun 23, 2020 at 3:19
  • Ops, corrected that, but still not working Commented Jun 23, 2020 at 3:31

1 Answer 1

1

How about avoiding element match and do this instead?

db.surveys.find({
    $or: [{"participants.answers.question1":"abc"}, {"participants.answers.question2":"xyz"}]
})
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that works! Thanks! Any idea why $elemMatch doesn't work in that case?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.