【发布时间】:2021-12-06 23:59:05
【问题描述】:
我有包含动态字段的文档,我需要为给定的复杂查询条件找到匹配记录的计数
示例实体
@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:spring-data-mongodb:3.1.1
【问题讨论】:
标签: java mongodb aggregation-framework spring-data-mongodb