MongoDB 4.4聚合$match阶段条件查询报错及解决方法咨询
MongoDB 4.4 聚合$match阶段条件查询的正确写法
针对你需求的条件逻辑,报错MongoError: FieldPath field names may not contain '.'是因为在常规查询条件中错误混用了聚合表达式的字段引用方式,正确的做法是通过$expr结合$cond实现条件判断,具体代码如下:
{ $match: { $expr: { $cond: { if: { $eq: ["$type", "country"] }, then: { $and: [ { $eq: ["$countryState.status", "Confirmed"] }, { $eq: ["$countryState.prop", "high"] } ] }, else: true } } } }
代码逻辑说明:
$expr关键字允许在$match阶段使用聚合表达式,这是实现复杂条件判断的核心$cond实现分支逻辑:- 当
type字段等于country时,通过$and同时校验嵌套字段countryState.status为Confirmed、countryState.prop为high - 当
type字段不等于country时,返回true,表示匹配所有文档
- 当
内容的提问来源于stack exchange,提问作者Mehdi M
相关产品推荐
相关产品推荐

