MongoDB聚合$filter中AND内嵌套OR条件报错求助
解决MongoDB $filter中嵌套$or条件的报错问题
问题出在你直接把$$this.reported_at作为$or的条件项,MongoDB聚合表达式不支持这种写法,得用专门的操作符来判断字段存在性和null值。
正确写法示例
db.collection.aggregate([ { $addFields: { filteredDestinations: { $filter: { input: "$destinations", as: "item", cond: { $and: [ { $eq: ["$$item.type", 1] }, { $or: [ { $not: { $exists: "$$item.reported_at" } }, // 判断字段不存在 { $eq: ["$$item.reported_at", null] } // 判断字段值为null ] } ] } } } } } ])
报错原因说明
MongoDB聚合表达式里,不能直接用$$this.reported_at当作布尔条件(比如判断“是否存在”),必须通过$exists操作符检查字段是否存在,用$eq操作符比较值是否为null。你之前直接把$$this.reported_at放进$or条件里,MongoDB会将其识别为未定义的表达式,因此抛出“Unrecognized expression”错误。
简化写法(可选)
如果不需要严格区分“字段不存在”和“字段值为null”,可以直接用$eq: ["$$item.reported_at", null],因为MongoDB中该表达式会同时匹配这两种情况,这样$or条件可以简化:
cond: { $and: [ { $eq: ["$$item.type", 1] }, { $eq: ["$$item.reported_at", null] } ] }
内容的提问来源于stack exchange,提问作者Amaarockz
相关产品推荐
相关产品推荐

