>我有以下JSON结构:
{
"id": "5cea8bde0c80ee2af9590e7b",
"name": "Sofitel",
"pricePerNight": 88,
"address": {
"city": "Rome",
"country": "Italy"
},
"reviews": [
{
"userName": "John",
"rating": 10,
"approved": true
},
{
"userName": "Marry",
"rating": 7,
"approved": true
}
]
}
我想找到类似文档的列表,其中评论的所有评级值都符合特定标准,例如小于 8。上面的文件不符合评论评级为 10 的条件。
使用以下形式的 Querydsl,我仍然获得该文档
BooleanExpression filterByRating = qHotel.reviews.any().rating.lt(8);
您可以使用
$filter
和$match
来过滤掉不需要的事务。以下查询应该可以做到这一点:
注意:$filter中的cond
与您的条件相反。由于您需要小于 8 的ratings
,在这种情况下,您将需要大于或等于 8 的ratings
db.qHotel.aggregate([
{
$addFields: {
tempReviews: {
$filter: {
input: "$reviews",
as: "review",
cond: { $gte: [ "$$review.rating", 8 ] } // Opposite of < 8, which is >= 8
}
}
}
},
{
$match : {
tempReviews : [] // This will exclude the documents for which there is at least one review with review.rating >= 8
}
}
]);
最后的结果将包含名为 tempReviews
的空字段,您可以使用$project
将其删除。
编辑:
在此处查看示例。