如何对Mongo Db聚合框架的输出应用过滤器? [英] How to apply filter for output of aggregation framework of Mongo Db?

查看:80
本文介绍了如何对Mongo Db聚合框架的输出应用过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Mongo Db聚合的输出应用条件,但仍然不知道这个想法。这是我的示例文档:

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]
}

因此,如果我有一个要求,例如查找所有具有min(customer_review)> 5->的文档,则仅第二个文档是正确的。

So if I have a requirement like find all documents which has min(customer_review) > 5 -> only the second document is correct.

这是我获得文档的min(customerReview)的初始要点:

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"}}}
]);

会产生:

{
  "_id" : ObjectId("58ab1d6892bf3194a9719883"),
  "min_customer_review" : 5
},
{
  "_id" : ObjectId("58ab1d6892bf3194a9719883"),
  "min_customer_review" : 6
}

那么如何继续对聚合输出应用过滤器,以获取具有min_customer_review> 5的所有文档?

So how to continue apply filter for aggregation output to get all documents which has min_customer_review > 5?

还有一个问题,它是否可以应用第二个聚合,例如全部获取影片的min_customer_review> 5或average_expert_reviews> 6?

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" ?

谢谢大家

推荐答案

您可以使用 $ redact

$ redact 浏览文档并根据查询条件执行 $$ KEEP $$ PRUNE

$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"
            }
        }
    }]
);

您可以在 $ or 中包装更多条件

You can wrap more conditions in $or operator.

if 块中的值替换为

{ $or:[{$gt: [{ $min: "$customerReviews"}, 5 ] }, {$gt: [{ $avg: "$expertReviews"}, 6 ] } ]}

这篇关于如何对Mongo Db聚合框架的输出应用过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆