How to apply filter for output of aggregation framework of Mongo Db?

浪子不回头ぞ 提交于 2020-01-07 03:11:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!