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

时间:2019-04-13 20:54:41

标签: mongodb mongodb-query

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

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

但是,如果grades数组具有空值,我该如何删除它们,请尝试这样做,但不能给出正确的输出。

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分: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 }
    >