问题
I'm trying to apply condition for the output of the aggregation of Mongo Db but still do not figure out the idea. Here are my sample documents:
{
'id':1,
'customerReviews':[5,7,8],
'expertReviews':[9,8,9]
},
{
'id':1,
'customerReview':[6,7,7],
'expertReview':[4,8,9]
}
So if I have a requirement like find all documents which has min(customer_review) > 5 -> only the second document is correct.
Here is my initial point which get the min(customerReview) of documents:
db.getCollection('subscriber').aggregate([
{$unwind:"$customerReviews"},
{"$group":{
"_id":"$_id",
"min_customer_review":{"$min":"$customerReviews"}}}
]);
which produces:
{
"_id" : ObjectId("58ab1d6892bf3194a9719883"),
"min_customer_review" : 5
},
{
"_id" : ObjectId("58ab1d6892bf3194a9719883"),
"min_customer_review" : 6
}
So how to continue apply filter for aggregation output to get all documents which has min_customer_review > 5?
One more question, is it able to apply second aggregation, like "get all movies which has min_customer_review > 5 or average_expert_reviews > 6" ?
Thank u all
回答1:
You can use $redact
.
$redact
to go through document and perform $$KEEP
and $$PRUNE
on the query criteria.
db.subscriber.aggregate(
[{
$redact: {
$cond: {
if: {
$gt: [{
$min: "$customerReviews"
}, 5]
},
then: "$$KEEP",
else: "$$PRUNE"
}
}
}]
);
You can wrap more conditions in $or
operator.
Replace the value in if
block with
{ $or:[{$gt: [{ $min: "$customerReviews"}, 5 ] }, {$gt: [{ $avg: "$expertReviews"}, 6 ] } ]}
来源:https://stackoverflow.com/questions/42351601/how-to-apply-filter-for-output-of-aggregation-framework-of-mongo-db