问题描述
这些是我收藏中的文件
{ "_id" : 1, "quizzes" : [ 10, 6, 7 ], "labs" : [ 5, 8 ], "final" : 80, "midterm" : 75 ,"extraMarks":10}
{ "_id" : 2, "quizzes" : [ 9, 10 ], "labs" : [ 8, 8 ], "final" : 95, "midterm" : 80 }
{ "_id" : 3, "quizzes" : [ 4, 5, 5 ], "labs" : [ 6, 5 ], "final" : 78, "midterm" : 70 }
只有文档1的字段带有额外的标记:
Only Document 1 has a field extra marks:
现在我必须以最终" +中期" +"extraMarks"之和进行投影
Now i have to make a projection as a sum of "final"+"midterm"+"extraMarks"
我编写了一个投影查询,如下所示:
I have written a query for projection as follows:
db.students.aggregate([ { $project: { examTotal: { $add: [ "$final", "$midterm","$extraMarks" ] } } } ])
此查询为我提供了Document1和Doc2和Doc3的正确结果,因为该字段不存在,其取总和为null.
This query is giving me correct result for Document1 and for Doc2 and Doc3, as the field doesnt exist its giving sum as null.
是否可以检查该字段是否不为null并添加查询本身.对此有任何建议吗?
Is it possible to check if the field is not null and add in the query itself..Any suggestions for this?
查询Mongo DB中是否有类似于nvl(在SQL中)的功能?
Is there any functionality similar to nvl (in SQL) in the queries Mongo DB?
推荐答案
您可以进行两个投影,第一个使用 $ ifNull ,它类似于nvl:
You can do two projections, the first using $ifNull which is similar to nvl:
db.students.aggregate([
{ $project: { final: 1, midterm: 1, extraMarks: { $ifNull: [ "$extraMarks", 0 ] } } },
{ $project: { examTotal: { $add: [ "$final", "$midterm","$extraMarks" ] } } }
])
这篇关于$ add,某些字段为Null,返回总和值为Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!