2017-01-29 51 views
1

我有这样的猫鼬模型模式MongoDB中找到数组的长度超过指定大小

const postSchema = new Schema({ 

    title: String, 

    headline: [{ 
    kind: String, 
    id: Schema.Types.ObjectId, 
    content: String, 
    relevance: Number, 
    _id: false 
    }], 

}); 

我想找到模型,其中headline数组的长度大于数据库更大的X

我有这个疑问:

const query = { 
     'headline.kind': 'topic', 
     'headline.id': topicId, 
     'headline':{ 
      '$size':{ 
       '$gt': x 
      } 
     } 
    }; 

但是当我用这个,我得到:

{ MongooseError: Cast to number failed for value "{ '$gt': 2 }" at path "headline" 
    at CastError (/home/oleg/WebstormProjects/lectal/api/node_modules/mongoose/lib/error/cast.js:26:11) 

任何人都知道构建此查询的正确方法? (在我的代码中,我只是硬编码x的数字2)。

回答

2

因为你可以用"dot notation做到这一点,最有效的方式,至少’n + 1元素,然后返回。

因此而不是写{ "$gt": 2 }你,而不是寻找“第三”元素的索引值的情况下(从零指数第三个是2):

{ "headline.2": { "$exists": true } } 

$exists运算符正在查找该给定索引处存在的元素,并且当条件满足时,该阵列必须至少具有该长度,因此“大于2”

还注意到您的查询条件希望匹配数组元素上的多个属性,为此,您实际上使用$elemMatch,否则条件实际上适用于在数组中匹配任意元素,而不仅仅是与$elemMatch一样具有“两个”条件的元素。

{ 
    "headline": { "$elemMatch": { "kind": "topic", "id": topicId } }, 
    "headline.2": { "$exists": true } 
} 

做“动态”,我们只是构建查询生成从参数的关键是:

const query = { 
    "headline": { "$elemMatch": { "kind": "topic", "id": topicId } } 
}; 

query['headline.'+x] = { "$exists": true } 
相关问题