'MongoTemplate matching referenced object in aggregation
Using MongoTemplate with Criteria to match a Document against a related User as below:
var query = new Query().with(pageable);
query.addCriteria(Criteria.where("user").is(user));
query.addCriteria(Criteria.where("date").gte(startDate).lt(endDate));
mongoTemplate.find(query, MyClass.class);
results in the correct query being generated by Spring:
{
"user": {
"$oid": "621bd3461be5bb603f139353"
},
"date": {
"$gte": {
"$date": "2021-10-20T00:00:00Z"
},
"$lt": {
"$date": "2021-10-21T00:00:00Z"
}
}
}
however, when using the same Criteria using the aggregation framework, in a $match operation as in:
var filterMatch = Aggregation.match(
new Criteria()
.andOperator(
Criteria.where("user").is(user),
Criteria.where("date").gte(startDate).lt(endDate)
)
);
the logs show the whole User Document is being used to match:
{
"$match": {
"$and": [
{
"user": {
"_id": {
"$oid": "621bd3461be5bb603f139353"
},
"login": "xxx",
"password": "$2a$10$hqx1bowiYiqP",
"email": "xxx",
"activated": true,
"resetKey": "Yt3cXyRvU7QaM58ggQC0",
"createdBy": "anonymousUser",
"createdDate": {
"$date": "2022-02-27T19:38:46.749Z"
},
"lastModifiedBy": "anonymousUser",
"lastModifiedDate": {
"$date": "2022-03-05T13:10:59.761Z"
}
}
},
{
"date": {
"$gte": {
"$date": "2022-02-01T00:00:00Z"
},
"$lt": {
"$date": "2022-02-02T00:00:00Z"
}
}
}
]
}
}
Also, for some reason the latest doesn't work and returns nothing.
This one-to-many relation in the entities is done using @DocumentReference
@DocumentReference
@Indexed
@Field("user")
@JsonIgnore
private User user;
What's one correct way to achieve this with the aggregation framework in Spring Mongo?
Solution 1:[1]
For those who find this question in the future...
Using @DocumentReference inserts only the id of the foreign document in the current document, so doing
var filterMatch = Aggregation.match(
new Criteria()
.andOperator(
Criteria.where("user").is(new ObjectId(userId)),
Criteria.where("date").gte(startDate).lt(endDate)
)
);
solved my problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | luso |
