在数组中删除空值后聚合函数以投影数组大小

问题描述 投票:1回答:2

我的主要目标是打印标题的等级数大于4,我可以通过以下查询实现它,

db.students.aggregate({$project : { title:1 ,_id : 0,  count: {$size : "$grades"}}},{$match: {"count": {$gt:4}}})

但是如果grade数组有空值我怎么能删除它们,试过这个但没有给出正确的输出。

db.students.aggregate({$project : { title:1 ,_id : 0,  count: {$size : "$grades"}}},{$match: {"count": {$gt:4},grades : {$ne:''}}})
mongodb mongodb-query
2个回答
0
投票

在运行$filter之前,您可以使用grades删除空的$size

db.students.aggregate([
    {$project : { title:1 ,_id : 0,  count: { $size : { $filter: { input: "$grades", cond: { $ne: [ "$$this", '' ] } } }}}},
    {$match: {"count": {$gt:4}}}
])

0
投票

让我们一步一步地解释不同的不同查询:

集合grades中的所有可能值:

> db.grades.find()
    { "_id" : ObjectId("5cb2ff50d33f6ed856afe577"), "title" : "abc", "grades" : [ 12, 23, 1 ] }
    { "_id" : ObjectId("5cb2ff55d33f6ed856afe578"), "title" : "abc", "grades" : [ 12, 23 ] }
    { "_id" : ObjectId("5cb2ff5cd33f6ed856afe579"), "title" : "abc", "grades" : [ 12, 23, 10, 100, 34 ] }
    { "_id" : ObjectId("5cb2ff63d33f6ed856afe57a"), "title" : "abc", "grades" : "" }
    { "_id" : ObjectId("5cb2ff66d33f6ed856afe57b"), "title" : "abc", "grades" : [ ] }
    { "_id" : ObjectId("5cb2ff6bd33f6ed856afe57c"), "title" : "abc", "grades" : [ 1, 2, 3, 4, 5 ] }

刚刚将空成绩记录过滤为:

> db.grades.aggregate([{$match: {grades: {$ne:''}} }])

    { "_id" : ObjectId("5cb2ff50d33f6ed856afe577"), "title" : "abc", "grades" : [ 12, 23, 1 ] }
    { "_id" : ObjectId("5cb2ff55d33f6ed856afe578"), "title" : "abc", "grades" : [ 12, 23 ] }
    { "_id" : ObjectId("5cb2ff5cd33f6ed856afe579"), "title" : "abc", "grades" : [ 12, 23, 10, 100, 34 ] }
    { "_id" : ObjectId("5cb2ff66d33f6ed856afe57b"), "title" : "abc", "grades" : [ ] }
    { "_id" : ObjectId("5cb2ff6bd33f6ed856afe57c"), "title" : "abc", "grades" : [ 1, 2, 3, 4, 5 ] }

现在将等级计数值与所需的其他列一起投影到变量中。

> db.grades.aggregate([{$match: {grades: {$ne:''}} }, {$project: {_id:0, title:1, count: {$size: "$grades"}  } }])

    { "title" : "abc", "count" : 3 }
    { "title" : "abc", "count" : 2 }
    { "title" : "abc", "count" : 5 }
    { "title" : "abc", "count" : 0 }
    { "title" : "abc", "count" : 5 }

现在匹配等级数组大于4的所需条件,如下所示:

> db.grades.aggregate([{$match: {grades: {$ne:''}} }, {$project: {_id:0, title:1, count: {$size: "$grades"}  } }, {$match: {count: {$gte: 4}}}  ])

    { "title" : "abc", "count" : 5 }
    { "title" : "abc", "count" : 5 }
    > 
© www.soinside.com 2019 - 2024. All rights reserved.