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

使用$all和$regex查询MongoDB数组小写内容报错:no $ expressions in $all

解决MongoDB $all + $regex 查询报错的问题

嘿,我来帮你分析并解决这个报错!你遇到的MongoError: no $ expressions in $all,本质是因为MongoDB的$all操作符不接受直接把$regex作为顶级表达式放在它的数组里。$all要么需要具体的数值(比如字符串、数字),要么需要针对数组元素的完整查询结构,你当前的写法不符合它的语法规则。

接下来根据你的实际需求,给你几种可行的解决方案:

需求1:查询input数组中至少有一个元素匹配正则

这应该是你最可能的需求(毕竟你只传了一个正则条件),这种情况根本不需要用$all,直接对input字段使用正则匹配就行:

dbo.collection("intent").find({ 
  input: { $regex: new RegExp("^" + message.toLowerCase(), "i") } 
}).toArray(function(err, result) { });

或者更简洁的写法,直接传递RegExp对象:

const matchRegex = new RegExp("^" + message.toLowerCase(), "i");
dbo.collection("intent").find({ input: matchRegex }).toArray(function(err, result) { });

需求2:用$all匹配多个正则条件

如果你确实需要$all(比如要求input数组同时包含匹配多个正则的元素),直接把RegExp对象放进$all数组里就好,不用套$regex:

// 示例:同时匹配以message1和message2开头的元素
const regex1 = new RegExp("^" + message1.toLowerCase(), "i");
const regex2 = new RegExp("^" + message2.toLowerCase(), "i");
dbo.collection("intent").find({ 
  input: { $all: [ regex1, regex2 ] } 
}).toArray(function(err, result) { });

需求3:查询input数组中所有元素都匹配正则

如果你的目标是数组里的每一个元素都符合这个正则规则,可以结合$elemMatch和$not来实现:

const matchRegex = new RegExp("^" + message.toLowerCase(), "i");
dbo.collection("intent").find({ 
  input: {
    $not: { $elemMatch: { $not: matchRegex } }
  }
}).toArray(function(err, result) { });

这个写法的逻辑很简单:不存在任何一个元素不匹配该正则,也就意味着所有元素都符合要求。

内容的提问来源于stack exchange,提问作者Ibid Athoillah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:37:19