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

如何在MongoRepository中使用All运算符(无需@Query)

Got it, let's break down what's happening here and how to fix it.

First, the error you're seeing (Invalid derived query! No property all found for type String!) makes total sense because of how Spring Data MongoDB handles derived query method names:

  • The All suffix in derived queries is designed for collection-type fields (like List<String> or Set<String>). It tells Spring Data to generate a MongoDB $all query, which checks if the field's array contains every element from the input set.
  • Since your firstName is a single String field, Spring Data thinks you're trying to access a property named all on the String type (which doesn't exist), hence the error.

Now, let's cover the two common scenarios to get the $all behavior you want, without using @Query:

Scenario 1: Your firstName is a single String field

MongoDB's $all operator doesn't make direct sense for a single string (a string can't equal multiple values at once). But if you actually want to find documents where firstName contains all the keywords from your input set, use the ContainingAll suffix:

List<User> findByFirstNameContainingAll(Set<String> keywords);

This will generate a query like:

{ "firstName": { "$all": [/keyword1/, /keyword2/] } }

Which matches any document where firstName includes every keyword from your input set.

Scenario 2: Your field is a collection type (e.g., List<String> firstNames)

If your field is actually an array/list of strings (maybe you named it firstName by mistake), adjust your method name to target the collection field correctly. You can use either the All suffix:

List<User> findByFirstNamesAll(Set<String> names);

Or the more explicit ContainsAll suffix (both work the same):

List<User> findByFirstNamesContainsAll(Set<String> names);

Both of these will generate the $all query you're looking for, matching documents where the firstNames array includes every element from your input set.

To recap:

  • Use ContainingAll for single-string fields when you need to match all substrings/keywords
  • Use All or ContainsAll for collection-type fields when you need to match all elements in the input set

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:34:01