0

I have the following model...

{
    username: 'bob',
    data: [
        {
            sport: 'football',
            events: [
                {
                    event: 1,
                    _id: 'h4jh234ht34j'
                },
                {
                    event: 2,
                    _id: '4h326ol2j3ld'
                },
                {
                    event: 2,
                    _id: 'fdsfasdfa3ws'
                }
                // ... more events
            ]
        },
        {
            sport: 'cricket',
            events: [
                {
                    event: 3,
                    _id: 'hd2g234ht3gj'
                },
                {
                    event: 2,
                    _id: '33326oldwqld'
                },
                {
                    event: 6,
                    _id: '461fa24gsa3s'
                }
                // ... more events
            ]
        },
        // ... more sports
    ]
}

Is there a way I can query this database to find any event objects where the event property equals 2? I want the query to return an array of objects for all the events from the different collections where the event = 2. Is this possible, or does the events array need to be an immediate ancestor of the "data" property?

2
  • Do you want the whole "bob" user document or just the events? Commented Aug 5, 2021 at 14:56
  • just the events Commented Aug 5, 2021 at 17:09

1 Answer 1

1

If you want to find the whole user document that contains some id you can do it just like this Playground 1

If you just want the matched events you could do it with $unwinds. Playground 2

Finally is you just want the event data, you could use $replaceRoot to get your expected result. Playground 3

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

2 Comments

Thank you, but although the model is what I want for the 2nd playground, the query returns the entire document when an object matches, but I only want it to return the object
@willmahon Edited with a 3rd playground just with the events info.

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.