【问题标题】:Mongoose - Find documents where array doesn't have any matchesMongoose - 查找数组没有任何匹配项的文档
【发布时间】:2019-06-29 18:31:36
【问题描述】:

这是我的收藏的架构:

{
    _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: ??? } }
});

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 是的!这正是我所需要的。另外,我不知道您可以对数组中的对象使用点表示法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2019-05-06
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多