我的文档中包含动态字段,我需要根据给定的复杂查询条件查找匹配记录的计数
示例实体
@Document(collection = "UserAttributes")
public class UserAttributesEntity {
@Id
@Getter
private String id;
@NotNull
@Size(min = 1)
@Getter @Setter
private String userId;
@NotNull
@Getter @Setter
private Map<String, Object> attributes = new HashMap<>();
}
示例数据
{
"_id" : ObjectId("6164542362affb14f3f2fef6"),
"userId" : "89ee6942-289a-48c9-b0bb-210ea7c06a88",
"attributes" : {
"age" : 61,
"name" : "Name1"
}
},
{
"_id" : ObjectId("6164548045cc4456792d5325"),
"userId" : "538abb29-c09d-422e-97c1-df702dfb5930",
"attributes" : {
"age" : 40,
"name" : "Name2",
"location" : "IN"
}
}
需要查询表达式
"((attributes.name == 'Name1' && attributes.age > 40) OR (attributes.location == 'IN'))
$match的MongoDB聚合查询如下所示,但无法通过spring mongo db API获得相同的查询:
{
$expr:
{
"$and": [{
"$gt": ["$attributes.age", 40]
}, {
"$eq": ["$attributes.name", "Name2"]
}]
}
}
我错过什么了吗?
库使用:数据org.springframework.data库:3.1.1
3条答案
按热度按时间ao218c7q1#
您可以实现自己的
AggregationOperation
来处理各种情况。我还没有尝试过自己的代码,但应该是这样的:并以这种方式调用它(以匹配您问题查询):
ve7v8dk22#
这个项目阶段允许我们使用查询表达式,我把我的方法转换到下面来达到结果:
83qze16e3#
在spring-data-mongodb库中仍然不支持
$expr
操作符。但是有一个使用MongoTemplate的解决方案来解决这个问题-Aggregation.match()提供了一个重载方法,它接受
AggregationExpression
作为参数。$match运算子的AggregationExpression使用范例-
以上代码相当于query -
问题的代码应该是这样的-