mongodb - Can I use "$first" operator on two fields in a "$group" operation in mongo db? -


consider dataset

 { "_id" : { "$oid" : "aaa" }, "student_id" : 0, "type" : "exam", "score" : 54.6535436362647 }     { "_id" : { "$oid" : "bbb" }, "student_id" : 0, "type" : "quiz", "score" : 31.95004496742112 }     { "_id" : { "$oid" : "ccc" }, "student_id" : 0, "type" : "homework", "score" : 14.8504576811645 }     { "_id" : { "$oid" : "ddd" }, "student_id" : 0, "type" : "homework", "score" : 63.98402553675503 }     { "_id" : { "$oid" : "eee" }, "student_id" : 1, "type" : "exam", "score" : 74.20010837299897 }     { "_id" : { "$oid" : "fff" }, "student_id" : 1, "type" : "quiz", "score" : 96.76851542258362 }     { "_id" : { "$oid" : "ggg" }, "student_id" : 1, "type" : "homework", "score" : 21.33260810416115 }     { "_id" : { "$oid" : "hhh" }, "student_id" : 1, "type" : "homework", "score" : 44.31667452616328 } 

say, each student, need find minimum score , corresponding document_id(_id).

here pipeline

pipeline = [ {"$sort":{"student_id":1,"score":1 } }, {"$group": {"_id":"$student_id","mscore":{"$first":"$score"},"docid":{"$first":"$_id"} } }, {"$sort":{"_id":1}},  {"$project":{"docid":1,"_id":0}} ] 

while working fine, not sure whether because have right query or whether because of way data stored.

here stragery

sort student_id, score
group student_id , first on score, give student_id, min_score

now, need doc_id(_id) min_score, using first on field also. correct?

let's after sort, need entire first document, should apply first on each , every field or there other way this?

to entire first document after sorting, apply $first operator on system variable $$root references root document, i.e. top-level document, being processed in $group operator pipeline stage. pipeline this:

var pipeline = [     {         "$sort": { "score": 1 }     },     {         "$group": {             "_id": "$student_id",             "data": { "$first": "$$root" }         }     },     {         "$project": {             "_id": "$data._id",             "student_id": "$data.student_id",             "type": "$data.type",             "lowest_score": "$data.score"         }     } ] 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -