Cancel in mongodba seems unclear to me

I'm fighting redact right now, and I'm not sure to figure it out.

I just read the docs and tried using redact for collector ratings (it comes from mongodb online learning)

The document in the "grades" collection is as follows:

{ "_id" : ObjectId("50b59cd75bed76f46522c34e"), "student_id" : 0, "class_id" : 2, "scores" : [ { "type" : "exam", "score" : 57.92947112575566 }, { "type" : "quiz", "score" : 21.24542588206755 }, { "type" : "homework", "score" : 68.19567810587429 }, { "type" : "homework", "score" : 67.95019716560351 }, { "type" : "homework", "score" : 18.81037253352722 } ] } 

I am using the following query:

 db.grades.aggregate([ { $match: { student_id: 0 } }, { $redact: { $cond: { if: { $eq: [ "$type" , "exam" ] }, then: "$$PRUNE", else: "$$DESCEND" } } } 

]);

With this query, each exam type will be found, this supporting document should be excluded. And it works, the result is:

 { "_id" : ObjectId("50b59cd75bed76f46522c34e"), "student_id" : 0, "class_id" : 2, "scores" : [ { "type" : "quiz", "score" : 21.24542588206755 }, { "type" : "homework", "score" : 68.19567810587429 }, { "type" : "homework", "score" : 67.95019716560351 }, { "type" : "homework", "score" : 18.81037253352722 } ] } 

but if I invert the condition, I expect that only exams will be saved as a result:

 if: { $eq: [ "$type" , "exam" ] }, then: "$$DESCEND", else: "$$PRUNE" 

however, the result is empty.

I don’t understand why the attached exam document is not included.

+5
source share
1 answer

The $redact begins with the root document and its fields, and only when this document fulfills the $$DESCEND condition, it checks the subdocuments included in this document. This means that the first thing $ redact does with your document is investigating this:

 { "_id" : ObjectId("50b59cd75bed76f46522c34e"), "student_id" : 0, "class_id" : 2, "scores" : [] // Some array. I will look at this later. } 

He doesn't even find the type field here, so $eq: [ "$type" , "exam" ] is false. What did you say $ redact when the condition is false? else: "$$PRUNE" , so the whole document is cropped before considering the subdocuments.

As a workaround, check if $type either "exam" or does not exist. You clearly did not ask for a working solution, so I will leave this exercise for you to figure out how to do it.

+8
source

All Articles