猫鼬-查找数组不匹配的文档

时间:2019-02-05 20:53:26

标签: arrays node.js mongodb mongoose

这是我的收藏的模式:

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

如果我有["spanish", "french"]种语言数组,如何找到Collection.translations没有针对数组中至少一种语言的对象的所有文档?

例如,应选择以下选项:

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

但不是这些:

{
    _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"
    }]
}

这是我到目前为止所拥有的:

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

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找$nin运算符,请尝试:

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