$ match阶段未在MongoDB聚合中提供任何输出

时间:2018-12-27 09:52:20

标签: mongodb aggregation-framework

我需要打印的文档超过同一集合中一个字段的平均值。

在聚合管道中,我没有在$match阶段(下一个阶段)使用avg_pmnt参数

对于以下代码

db.payments.aggregate([
    {$group: {
        "_id":1, 
        "avg_pmnt": {$avg: "$AMOUNT"}, 
        "AMNT": {$push: "$AMOUNT"}
    } },
    {$unwind: "$AMNT"},
    {$project: {avg_pmnt: "$avg_pmnt", AMNT: "$AMNT"}},
])

我得到以下输出:

{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 14191 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 32642 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 33348 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 45864 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 82261 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 7565 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 44895 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 19502 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 47924 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 49524 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 50219 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 1491 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 17876 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 34638 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 101245 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 85411 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 11044 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 83598 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 6067 }
{ "_id" : 1, "avg_pmnt" : 32431.65567765568, "AMNT" : 14571 }

输入"it"以获取更多

但是我要过滤它们

所以,我尝试了这个:

db.payments.aggregate([
    {$group: {
        "_id":1, 
        "avg_pmnt": {$avg: "$AMOUNT"}, 
        "AMNT": {$push: "$AMOUNT"}
    } },
    {$unwind: "$AMNT"},
    {$project: {avg_pmnt: "$avg_pmnt", AMNT: "$AMNT"}},
    {$match: {AMNT: {$gt: "$avg_pmnt"} }}
])

我没有收到任何文件(空集)。

我也尝试过

db.payments.aggregate([
    {$group: {
        "_id":1, 
        "avg_pmnt": {$avg: "$AMOUNT"}, 
        "AMNT": {$push: "$AMOUNT"}
    } },
    {$unwind: "$AMNT"},
    {$project: {avg_pmnt: "$avg_pmnt", AMNT: "$AMNT"}},
    {$match: {AMNT: {$gt: 1} }}
])

我将获取所有文档,因为每个文档都满足条件。

2 个答案:

答案 0 :(得分:2)

您还可以使用$redact在同一文档字段中进行比较并过滤文档

db.payments.aggregate([ 
    {$group: { "_id":1, "avg_pmnt": {$avg: "$AMOUNT"}, "AMNT": {$push: "$AMOUNT"} } }, 
    {$unwind: "$AMNT"}, 
    {$project: {avg_pmnt: "$avg_pmnt", AMNT: "$AMNT"}}, 
    {$redact :{$cond : [{$gt: ["$AMNT", "$avg_pmnt" ]},"$$DESCEND","$$PRUNE"]}}
])

答案 1 :(得分:1)

在尝试比较$match阶段内的两个字段时,应使用$expr

db.payments.aggregate([ 
    {$group: { "_id":1, "avg_pmnt": {$avg: "$AMOUNT"}, "AMNT": {$push: "$AMOUNT"} } }, 
    {$unwind: "$AMNT"}, 
    {$project: {avg_pmnt: "$avg_pmnt", AMNT: "$AMNT"}}, 
    {$match: { $expr: { $gt: [ "$AMNT", "$avg_pmnt" ] } }  } 
])