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] } ] } } } } } ])
说明
$elemMatch精准定位Fields数组中FieldId为"amount"的元素$expr允许在查询条件中使用聚合运算符,实现类型转换与数值判断- 新增的
$ne判断避免null值导致的转换错误 - 若需匹配大于指定数值(如100),直接替换
0为目标数值即可
内容的提问来源于stack exchange,提问作者Mani J
相关产品推荐
相关产品推荐

