1

I have this schema:

new mongoose.Schema({
    providers : [{
            provider: { type: String, required: true },
            data : { type : String, unique: true }
        }]
});

For instance, an item can be :

providers: [{provider: "linkedin", data: "abcd"},
            {provider: "twitter", data: "efgh"}]

What I would like to search in Mongoose: provider == "linkedin" and data = "abcd".

Do you know how to achieve this?

1 Answer 1

5

Use $elemMatch to match multiple fields in the same element:

Model.find({providers: {$elemMatch: {provider: 'linkedin', data: 'abcd'}}})

The following would also work, but is more brittle as it would require an exact match of the element, with no extra fields and with the two fields in the same order.

Model.find({providers: {provider: 'linkedin', data: 'abcd'}})
Sign up to request clarification or add additional context in comments.

3 Comments

What's the advantage of using $elemMatch here instead of db.w.find({providers:{provider:"linkedin", data:"abcd"}}) ?
@SylvainLeroux That would work, but is more brittle as it would require an exact match of the element, with no extra fields and with the two fields in the same order.
Thank you for clarifying that. I was looking at the doc right now and just noticed that I've forgot about those limitations. Maybe worth mentioning that in your answer ?

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.