Spring 数据 - MongoDB - $regex 搜索

qum*_*uma 2 regex mongodb spring-data

我在我的应用程序中使用 Spring 数据和 MongoDB,我的存储库类之一如下所示:

public interface ProductRepository extends MongoRepository<Product, String> {

@Query("{$or : [{'name': { $regex: ?0, $options:'i' }}, {'description': { $regex: ?0, $options:'i' }}]}")
List<Product> findProductByRegexString(final String regexString);

...
}
Run Code Online (Sandbox Code Playgroud)

我这样调用这个方法:

public class ProductServiceTest extends AbstractServiceTest {

@Test
public void shouldSearchProductBySubString() throws BusinessException {

    final Tenant tenant = new Tenant();
    tenant.setName("TestTenant");
    final Tenant createdTenant = tenantService.create(tenant);
    Assert.assertNotNull(createdTenant);

    final Product product1 = new Product();
    product1.setName("Wander");
    product1.setDescription("Das ist das Test Produkt 1");
    product1.setTenant(createdTenant);
    final Product createdProduct1 = productService.create(product1);
    Assert.assertNotNull(createdProduct1);

    final Product product2 = new Product();
    product2.setName("Wunder baum");
    product2.setDescription("Ein different Produkt 2");
    product2.setTenant(createdTenant);
    final Product createdProduct2 = productService.create(product2);
    Assert.assertNotNull(createdProduct2);

    final List<Product> allProducts = productService.findAllProductsByTenant(createdTenant);
    Assert.assertEquals(2, allProducts.size());

    final List<Product> products = productService.findProductsByRegex("/^Wand/");
    Assert.assertEquals(1, products.size());
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作正常。如果我尝试使用这个字符:

正则表达式

例如:

final List<Product> products = productService.findProductsByRegex("/^Wand/");
Run Code Online (Sandbox Code Playgroud)

我没有得到任何字符串/^Wand/ 的结果 有 没有人有任何解释为什么它不适用于/^Wand/

use*_*814 5

/expression/ 是 shell 和 js 驱动程序中使用的替代语法。

对于 Java 驱动程序,您只需要使用 "^Wand"

尝试

final List<Product> products = productService.findProductsByRegex("^Wand");
Run Code Online (Sandbox Code Playgroud)

更多在这里