1.
Create collection Universities with the following data:
db.universities.insert([
{
country : 'Spain',
city : 'Salamanca',
name : 'USAL',
location : {
type : 'Point',
coordinates : [ -5.6722512,17, 40.9607792 ]
},
students : [
{ year : 2014, number : 24774 },
{ year : 2015, number : 23166 },
{ year : 2016, number : 21913 },
{ year : 2017, number : 21715 }
]
},
{
country : 'Spain',
city : 'Salamanca',
name : 'UPSA',
location : {
type : 'Point',
coordinates : [ -5.6691191,17, 40.9631732 ]
},
students : [
{ year : 2014, number : 4788 },
{ year : 2015, number : 4821 },
{ year : 2016, number : 6550 },
{ year : 2017, number : 6125 }
]
}
])
2. Create another collection called Courses
db.courses.insert([
{
university : 'USAL',
name : 'Computer Science',
level : 'Excellent'
},
{
university : 'USAL',
name : 'Electronics',
level : 'Intermediate'
},
{
university : 'USAL',
name : 'Communication',
level : 'Excellent'
}
])
3. Identify the documents which specify that Spain is the value of the field country, and
Salamanca is the value of the field city.
Db.universities.aggregate([{$match:{country:”Spain”, city:”Salamanca”}}])
4. Using Project command display only Country, City and Name from the above data.
Db.universities.aggregate([{$project:{_id:0, country:1, city:1, name:1}}])
5. Display the number of documents per University.
Db.universities.aggregate([{$group:{_id:”$name”, count:{$sum:1}}}])
6. Using $out command
This is an unusual type of stage because it allows you to carry the results of your
aggregation over into a new collection, or into an existing one after dropping it, or even
adding them to the existing documents
db.universities.aggregate([
{ $group : { _id : '$name', totaldocs : { $sum : 1 } } },
{ $out : 'aggResults' }
])
Now, we check the content of the new ‘aggResults’ collection:
db.aggResults.find().pretty()
7. Using $unwind command
db.universities.aggregate([
{ $match : { name : 'USAL' } },
{ $unwind : '$students' }
]).pretty()
8. Using $sort command
Sort the documents obtained as a result of the $unwind stage by the number of students in
descending order. In order to get a lesser output, project only the year and the number of
students.
db.universities.aggregate([
{ $match : { name : 'USAL' } },
{ $unwind : '$students' },
{ $project : { _id : 0, 'students.year' : 1, 'students.number' : 1 } },
{ $sort : { 'students.number' : -1 } }
]).pretty()