MongoDB - Querying Nested Documents
Create a collection with a nested document as shown below
db.nested.insert({name:"satish",cat1:{eng:40,phy:30,chem:20}});
db.nested.insert({name:"mathew",cat1:{eng:90,phy:95,chem:80}});
Display the english marks for all students
db.nested.find({},{"cat1.eng":1})
Display the cat1 marks for student by name mathew
db.nested.find({name:"mathew"},{name:1,"cat1.eng":1,_id:0});
Find the sum of all the english marks scored in cat1
db.nested.aggregate({$project:{"cat1.eng":1}},{$group:{_id:"cat1.eng",total_marks:{$sum:"$cat1.eng"}}});
Find the average of all the english marks scored in cat1
db.nested.aggregate({$project:{"cat1.eng":1}},{$group:{_id:"cat1.eng",total_marks:{$avg:"$cat1.eng"}}});