【问题标题】:Reverse Regex Selection with Spring MongoDB使用 Spring MongoDB 反向正则表达式选择
【发布时间】:2017-12-07 12:32:10
【问题描述】:

我有一个包含以下对象的 mongo 集合:

[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]

尝试将_entityType 附加到所有文档的id 中,其中它不存在于id id 的末尾(上述情况下的第一个对象)。

在 Spring 中使用 mongo,但我已经坚持第一步,即获取所有 id 中没有 entityType 的对象。

用正则表达式考虑这样的事情,但我不确定它应该是什么样子:

Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );

【问题讨论】:

    标签: java regex spring mongodb spring-data-mongodb


    【解决方案1】:

    您可以通过“^”(“”正则表达式开始)构建您的正则表达式。

    因此,您需要一个指向所有文档并检查此过滤器的函数

        List<Document> result = new ArrayList<Document>();
        StringBuilder idPrefix = new StringBuilder();
        idPrefix.append("^");
        idPrefix.append(idCode);
        idPrefix.append("_");
        List<Bson> filters = new ArrayList<Bson>();
        filters.add(Filters.regex("_id", keyPrefix.toString()));
        for (Document d : yourCollections.find(Filters.and(filters)))
            list.add(d);
    

    【讨论】:

      【解决方案2】:

      您实际上想要一个“反向正则表达式”,因为您需要使用文档中的数据才能匹配另一个字段。

      目前,您实际上只能使用 MongoDB 使用 $where 来执行此操作,它会评估服务器上的 JavaScript。所以对于spring mongo,你需要BasicQuery,所以我们可以从BasicDBObjectCode原语构造:

          BasicDBObject basicDBObject = new BasicDBObject("$where",
                  new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));
      
          BasicQuery query = new BasicQuery(basicDBObject);
      

      这将测试文档中的"id" 字段,以查看它是否与“字符串末尾”处entityType 的值匹配,而不考虑“大小写”。 !Not 条件,因此逻辑的“反向”应用于字段实际以这种方式结束的“不匹配”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        相关资源
        最近更新 更多