Java 使用Spring MongoDB进行反向正则表达式选择

Java 使用Spring MongoDB进行反向正则表达式选择,java,regex,spring,mongodb,spring-data-mongodb,Java,Regex,Spring,Mongodb,Spring Data Mongodb,我有一个mongo集合,其中包含以下对象: [ { "_id" : "a2d", "entityType" : "Location", "type" : "STRING", }, { "_id" : "a1_order", "entityType" : "Order", "type" : "STRING", } ] 试图将\u entityType附加到所有文档的id中,如果它不在id的末尾(在上述情况下是第一个对象) 将mongo与Spring

我有一个mongo集合,其中包含以下对象:

[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]
试图将
\u entityType
附加到所有文档的
id
中,如果它不在id的末尾(在上述情况下是第一个对象)

将mongo与Spring结合使用,但我已经完成了第一步,即获取id中没有entityType的所有对象

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

Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );
实际上,这里需要一个“reverse regex”,因为您需要使用文档中的数据来匹配另一个字段

目前,您只能使用MongoDB来实现这一点,它在服务器上评估JavaScript。因此,对于spring mongo,您需要的是,因此我们可以从
BasicDBObject
code
Primative构建:

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

    BasicQuery query = new BasicQuery(basicDBObject);

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

您可以通过“^”(“”regex开头)构建正则表达式

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

    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);
List result=new ArrayList();
StringBuilder idPrefix=新的StringBuilder();
idPrefix.追加(“^”);
idPrefix.append(idCode);
idPrefix.追加(“”);
列表过滤器=新的ArrayList();
filters.add(filters.regex(“_id”,keyPrefix.toString());
对于(文档d:yourCollections.find(Filters.and(Filters)))
列表.添加(d);