APixel Visuals
APixel Visuals

Reputation: 1648

Mongoose - Find documents where array doesn't have any matches

Here's the schema for my collection:

{
    _id: {
        type: String,
        required: true,
        unique: true
    },
    translations: [{
        language: String,
        translation: String
    }]
}

If I have an array of languages, ["spanish", "french"], how can I find all the documents where Collection.translations doesn't have an object for at least one of the languages in the array?

For example, this should be selected:

{
    _id: "hello",
    translations: [{
        language: "not spanish",
        translation: "not hola"
    }]
}

But not these:

{
    _id: "hello",
    translations: [{
        language: "spanish",
        translation: "hola"
    }]
}
//and
{
    _id: "hello",
    translations: [{
        language: "spanish",
        translation: "hola"
    }, {
        language: "french",
        translation: "bonjour"
    }, {
        language: "not spanish",
        translation: "not hola"
    }]
}

Here's what I have so far:

Model.findOne({
    translations: { $elemMatch: { language: ??? } }
});

Upvotes: 1

Views: 270

Answers (1)

mickl
mickl

Reputation: 49985

I think you're looking for $nin operator, try:

Model.findOne({
   'translations.language': { $nin: [ "spanish", "french" ] }
});

Upvotes: 1

Related Questions