Mongodb发现数组长度大于指定大小

我有这个Mongoose模型模式

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) 

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

从我读过的是不可能做到这一点使用$size$gt

尝试使用$wherehttp://mongoosejs.com/docs/api.html#query_Query-%24where

对于最有效的方法,您可以通过指定n位置来使用“点符号 ”来完成此操作。 这基本上是说如果一个数组有“至less” n + 1元素然后返回它。

因此,而不是写{ "$gt": 2 } ,而是查找“第三个”元素(从零索引第三个为2)的索引值的存在:

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

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

还注意到你的查询条件想要匹配数组元素的几个属性,为此你实际上使用$elemMatch ,否则条件实际上适用于匹配数组中的任何元素,而不是只有与“两个”条件为$elemMatch

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

要做到这一点“dynamic”,我们只是build立从参数生成密钥的查询:

 const query = { "headline": { "$elemMatch": { "kind": "topic", "id": topicId } } }; query['headline.'+x] = { "$exists": true }