使用MongoDB Java Driver 4.1执行Atlas Search查询时遇wildcard路径必填错误
问题原因及解决方案
这个错误的根源是你构造Atlas Search wildcard查询的结构不对——你错误地用and操作符来包裹wildcard的参数,导致mongot(Atlas Search的后台服务)找不到它期望的path字段。
具体来说:
你的代码里用and(eq("path", "name"), eq("query", "dushan*"), ...)来组合参数,但wildcard查询的格式要求是一个包含path、query等属性的嵌套文档,而不是多个条件的逻辑与。这种写法会让最终发送给MongoDB的查询结构变成:
{ "$search": { "wildcard": { "$and": [ { "path": "name" }, { "query": "dushan*" }, { "allowAnalyzedField": true } ] } } }
mongot解析时,会去wildcard对象下找path字段,但实际path在$and数组里,自然就抛出了"'path' is required (from 'wildcard')"的错误。
修正后的代码
你需要把wildcard的参数直接构造为一个嵌套文档,这里提供两种简洁的写法:
写法一:用Document类构造(可读性更高)
testingCollection.aggregate(Arrays.asList( Aggregates.match( Filters.eq("$search", new Document("wildcard", new Document("path", "name") .append("query", "dushan*") .append("allowAnalyzedField", true) )) ) )).first();
写法二:用Java Driver的Bson构造器嵌套
testingCollection.aggregate(Arrays.asList( eq("$search", eq("wildcard", new Document() .append("path", "name") .append("query", "dushan*") .append("allowAnalyzedField", true) )) )).first();
这两种写法都会生成符合Atlas Search要求的查询结构:
{ "$search": { "wildcard": { "path": "name", "query": "dushan*", "allowAnalyzedField": true } } }
这样mongot就能正确识别path字段,执行你的wildcard查询了。
内容的提问来源于stack exchange,提问作者dushansilva
相关产品推荐
相关产品推荐

