Mongodb 查找数组长度大于指定大小

Ale*_*lls 3 mongoose mongodb node.js

我有这个猫鼬模型架构

const postSchema = new Schema({

  title: String,

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

});
Run Code Online (Sandbox Code Playgroud)

我想在数据库中找到headline数组长度大于 x 的模型

我有这个查询:

 const query = {
        'headline.kind': 'topic',
        'headline.id': topicId,
        'headline':{
            '$size':{
                '$gt': x
            }
        }
    };
Run Code Online (Sandbox Code Playgroud)

但是当我使用它时,我得到:

 { 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)
Run Code Online (Sandbox Code Playgroud)

有人知道构造这个查询的正确方法吗?(在我的代码中,我只是硬编码了 x 的数字 2。)

Nei*_*unn 6

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

因此,与其写作{ "$gt": 2 },不如寻找“第三个”元素的索引值的存在(从零索引第三个是 2 ):

{ "headline.2": { "$exists": true } }
Run Code Online (Sandbox Code Playgroud)

在$exists操作者正在寻找一个元素的给定索引处的存在,并且当满足条件时,则阵列必须至少该长度的,并且因此“大于两个”

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

{
  "headline": { "$elemMatch": { "kind": "topic", "id": topicId } },
  "headline.2": { "$exists": true }
}
Run Code Online (Sandbox Code Playgroud)

要“动态地”做到这一点,我们只需构建从参数生成键的查询:

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

query['headline.'+x] = { "$exists": true }
Run Code Online (Sandbox Code Playgroud)