You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询:字符串转Double并匹配数组对象数值条件

MongoDB查询需求与解决方案

样本集合

{
   "_id" : ObjectId("62aeb8301ed12a14a8873df1"),
   "Fields" : [ 
    {
        "FieldId" : "name",
        "Value" : [ "test_123" ]
    }, 
    {
        "FieldId" : "mobile",
        "Value" : [ "123" ]
    }, 
    {
        "FieldId" : "amount",
        "Value" : [ "300" ]
    }, 
    {
        "FieldId" : "discount",
        "Value" : null
    }
  ]
}

查询需求

匹配满足以下条件的记录:

  • 存在Fields.FieldId等于"amount"的元素
  • 对应元素的Fields.Value.0转换为Double后大于0(或指定数值)

注意事项

  • Fields.Value可能为null
  • 部分文档的Fields数组中可能没有FieldId为"amount"的元素

尝试过的无效聚合查询

db.form.aggregate([
{
  $match:
  {
    {
       $expr: {
          $ne: [
             { $filter: { 
                input: '$Fields', 
                  cond: { if: {$eq:["$$this.FieldId", "amount"]}, 
                          then:{$gte: [{$toDouble: "$$this.Value.0"}, 0]} }
                  } 
               }, []
           ]
         }
      }
    }
}])

解决方案(仅用$match实现)

完全可以仅通过$match阶段实现需求,核心是用$elemMatch结合$expr处理数组内的类型转换与条件判断:

db.form.aggregate([
  {
    $match: {
      Fields: {
        $elemMatch: {
          FieldId: "amount",
          $expr: {
            $and: [
              // 避免Value或Value.0为null时$toDouble报错
              { $ne: ["$Value", null] },
              { $ne: ["$Value.0", null] },
              // 转换为Double后大于0,可替换为指定数值
              { $gt: [{ $toDouble: "$Value.0" }, 0] }
            ]
          }
        }
      }
    }
  }
])

说明

  1. $elemMatch精准定位Fields数组中FieldId为"amount"的元素
  2. $expr允许在查询条件中使用聚合运算符,实现类型转换与数值判断
  3. 新增的$ne判断避免null值导致的转换错误
  4. 若需匹配大于指定数值(如100),直接替换0为目标数值即可

内容的提问来源于stack exchange,提问作者Mani J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:27:05