首页 > 解决方案 > 查找数组大小等于字段的位置

问题描述

我正在尝试查找数组大小等于字段值的所有文档。例如:

应该找到该文件:

{
  arr: ["one", "two", "three"],
  expected: 3
}

但不是这个:

{
  arr: ["one", "two", "three", "four"],
  expected: 2
}

我假设我必须使用某种形式的聚合,所以我决定使用$expr

$expr: { $eq: [{ $size: "$arr" }, { ??? }] }

标签: node.jsmongodbmongoose

解决方案


arr与您使用符号使用字段类似$,您必须使用expected字段

db.collection.find({ "$expr": { "$eq": [{ "$size": "$arr" }, "$expected"] })

推荐阅读