使用 $gte 或 $lte 查找文档,其中数字作为数组中的字符串值

Find documents with $gte or $lte which has numbers as string values in arrays

我有一个 MongoDB 集合,其中包含如下文档:

{
 "_id": ObjectId(.....),
 "name": "John",
 "contacts": [
    {
      "name": "henry",
      "age": "22"
    },
    {
      "name": "merry",
      "age": "12"
    }
 ]
}

我想查找 contacts.age 小于 20 的文档。我尝试了以下 mongo 查询但没有成功。谁能帮帮我?

document.Users.find({'$expr':{'$lte': [{'$toInt':'$contacts.age'}, '20'] }})

以上查询给出以下错误:

Query failed with error code 241 and error message 'Executor error during find command :: 
caused by :: 
Unsupported conversion from array to int in $convert with no onError value' on server

如果您想要所有文档(不做任何更改),您可以试试这个聚合查询:

这里的技巧是仅获取从条件 "$lte": [{"$toInt": "$$this"},20].

返回的数组中有一个 true 的文档

这意味着只会匹配具有匹配值(至少一个子文档)的数组的文档。

编辑最后的工作示例,使用两种方式确保数据:

  • $expr 之前使用 "contacts": { "$ne": null } 进入 $match 阶段以避免 map over null。
  • 使用 $convert 可以使用 onErroronNull 以防任何值不是数字且无法转换。
db.collection.aggregate([
  {
    "$match": {
      "contacts": {
        "$ne": null
      },
      "$expr": {
        "$in": [
          true,
          {
            "$map": {
              "input": "$contacts",
              "in": {
                "$lte": [
                  {
                    "$convert": {
                      "input": "$$this.age",
                      "to": "int",
                      "onError": "",
                      "onNull": ""
                    }
                  },
                  30
                ]
              }
            }
          }
        ]
      }
    }
  }
])

示例here