【问题标题】:Spring data - MongoDB - $regex search春季数据 - MongoDB - $regex 搜索
【发布时间】:2018-01-24 13:56:42
【问题描述】:

我在我的应用程序中使用 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);

...
}

我这样调用这个方法:

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());
    }
}

而且效果很好。 如果我尝试使用这个字符:

例如:

final List<Product> products = productService.findProductsByRegex("/^Wand/");

我没有得到字符串 /^Wand/ 的任何结果 有没有人解释为什么它不能与 /^Wand/ 一起使用。

【问题讨论】:

    标签: regex mongodb spring-data


    【解决方案1】:

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

    对于java驱动你只需要使用"^Wand"

    试试

    final List<Product> products = productService.findProductsByRegex("^Wand");
    

    更多here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多