1

I have the following document structure:

recipients: [
    {
        name: String,
        hidden: Boolean,
    },
    {
        name: String,
        hidden: Boolean,
    },
    // more ...
];

I want to query all documents for a given name and a given hidden value in the same object, meaning at the same index of the recipients array. How can I query for example "all documents for name = test and hidden = false" (where hidden is in the same object as the name)? I tried the following

const chats = await Model.find(
            {
                'recipients.name': name,
                'recipients.hidden': false,
            },

But this still returns the document because it does not seem to use those 2 conditions for the same object, but across all objects in the array.

1 Answer 1

1

Nevermind, got it. See the MongoDB docs for $elemMatch (https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#array-of-embedded-documents)

{ 
    "recipients": {
        "$elemMatch": {
            "name": name,
            "hidden": false 
        }, 
    }, 
}
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.