MongoDB聚合查询中$addFields处理多类型字段(字符串/数组)的问题求助
MongoDB聚合查询中$addFields处理多类型字段(字符串/数组)的问题求助
嘿,这个问题我之前也碰到过,MongoDB里处理字段类型不固定的情况确实容易踩坑,我来帮你解决~
问题根源
你的metadata.schemes字段存在两种类型:
- 有时是单个对象,此时
metadata.schemes._trail是字符串类型,可以直接用$substr处理 - 有时是对象数组,此时
metadata.schemes._trail会返回一个数组(包含数组内每个对象的_trail值),而$substr只能处理字符串,因此抛出can't convert from BSON type array to String的错误
解决方案
我们可以用$cond结合$isArray来判断字段类型,针对不同类型做不同处理。这里假设当schemes是数组时,你需要取数组第一个元素的_trail(如果业务需求是取其他元素或拼接所有值,可以调整逻辑):
修改后的完整聚合查询
db.ledger_scheme_logs.aggregate([ { $match: { "type": { $in: ["add", "edit"] } } }, { "$addFields": { "trail_beginning": { $substr: [ // 先判断schemes是否为数组,再取对应的_trail值 { $cond: { if: { $isArray: "$metadata.schemes" }, then: { $first: "$metadata.schemes._trail" }, // 取数组第一个元素的_trail else: "$metadata.schemes._trail" // 非数组时直接取_trail } }, 0, 36 ] } } }, { $group: { "_id": { "trail_beginning": "$trail_beginning" }, "count": { $sum: 1 }, "items": { $push: "$$ROOT" } } }, { "$sort": { count: -1 } } ])
额外优化(可选)
如果你的数组可能为空(没有元素),可以再加一层$ifNull来避免取$first时返回null导致$substr报错:
"trail_beginning": { $substr: [ { $cond: { if: { $isArray: "$metadata.schemes" }, then: { $ifNull: [{ $first: "$metadata.schemes._trail" }, ""] }, // 空数组时返回空字符串 else: { $ifNull: "$metadata.schemes._trail", "" } // 非数组但字段不存在时返回空字符串 } }, 0, 36 ] }
这样就能完美处理字段类型不固定的情况啦~
备注:内容来源于stack exchange,提问作者Ronak07
相关产品推荐
相关产品推荐

