Mongoose在数组中查找元素

时间:2016-02-05 00:18:20

标签: mongodb mongoose mongodb-query

我刚开始使用Mongoose并且遇到了寻找元素的问题......

我的架构包含一个subregions数组,我希望通过它code找到匹配的数组。架构如下:

 var schema = {
        name: {
            type: String,
            required: true
        }

        ...

        subRegions: [{
            name: {
                type: String,
                required: true
            },
            code: {
                type: String,
                required: true
            }
        }]

        ...

    };

我想出了

find({
    subRegions: {
        "$in": [{
            code: regionCode
        }]
    }
}).exec(...)

但这不起作用......

1 个答案:

答案 0 :(得分:6)

您的术语已关闭,因为该结构不是"多维"数组,因为它们在数组中有#34;数组"因此"维度"。这只是"对象"在数组中。

所以这里你的问题是一个基本的例子,让错误的方法参与其中。你不需要$in来搜索一个数组,而是需要一个" list / array"适用于该领域的论据。

简而言之,只需查找字段,然后使用"dot notation"

.find({ "subRegions.code": regionCode }).exec(...);

您只需要$in基本上$or条件,查找subRegions.code的替代值,因此当只有一个值匹配时您不需要

相关问题