使用 Spring MongoDB 反向正则表达式选择
Reverse Regex Selection with Spring MongoDB
我有一个 mongo 集合,其中包含如下对象:
[
{
"_id" : "a2d",
"entityType" : "Location",
"type" : "STRING",
},
{
"_id" : "a1_order",
"entityType" : "Order",
"type" : "STRING",
}
]
尝试将 _entityType
附加到所有文档的 id
中,它不存在于末尾 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 来代替 $where
, which evaluates JavaScript on the server. So for spring mongo, you need the BasicQuery
来做到这一点,所以我们可以从 BasicDBObject
和 Code
原语构造:
BasicDBObject basicDBObject = new BasicDBObject("$where",
new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));
BasicQuery query = new BasicQuery(basicDBObject);
这将测试文档中的 "id"
字段,看它是否与 "end of the string" 中 entityType
的值匹配,而不考虑 "case"。 !
是一个 Not
条件,因此逻辑的 "reverse" 应用于 "not match",字段实际上以这种方式结束。
您可以通过“^”构建您的正则表达式(“以”开头的正则表达式)。
因此您需要一个指向所有文档并检查此过滤器的函数
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);
我有一个 mongo 集合,其中包含如下对象:
[
{
"_id" : "a2d",
"entityType" : "Location",
"type" : "STRING",
},
{
"_id" : "a1_order",
"entityType" : "Order",
"type" : "STRING",
}
]
尝试将 _entityType
附加到所有文档的 id
中,它不存在于末尾 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 来代替 $where
, which evaluates JavaScript on the server. So for spring mongo, you need the BasicQuery
来做到这一点,所以我们可以从 BasicDBObject
和 Code
原语构造:
BasicDBObject basicDBObject = new BasicDBObject("$where",
new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));
BasicQuery query = new BasicQuery(basicDBObject);
这将测试文档中的 "id"
字段,看它是否与 "end of the string" 中 entityType
的值匹配,而不考虑 "case"。 !
是一个 Not
条件,因此逻辑的 "reverse" 应用于 "not match",字段实际上以这种方式结束。
您可以通过“^”构建您的正则表达式(“以”开头的正则表达式)。
因此您需要一个指向所有文档并检查此过滤器的函数
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);