$add with some fields as Null returning sum value as Null

孤街浪徒 提交于 2019-12-24 11:48:29

问题


These are the documents in my collection

{ "_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 }

Only Document 1 has a field extra marks:

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

This query is giving me correct result for Document1 and for Doc2 and Doc3, as the field doesnt exist its giving sum as null.

Is it possible to check if the field is not null and add in the query itself..Any suggestions for this?

Is there any functionality similar to nvl (in SQL) in the queries Mongo DB?


回答1:


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



回答2:


Use the $match stage, add it to the beginning of your pipeline {$match: {"your_field":{$exists: true}}}



来源:https://stackoverflow.com/questions/35250675/add-with-some-fields-as-null-returning-sum-value-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!