1. Database data description
#Collection: school
#Documents: stu
#Combination of fields: ID, student ID, name, telephone, gender, age, education background, remarks
#Initialize 20 items of datause school for (var num=1; num<=20; Num ++) {db.stu.insert({id:num, no: "SN"+num, name: "name"+num, tel: "1111111111", sex: "female ", age: num, school: "Graduate student ", remark:" Remarks "})}Copy the code
2. Common database operations
#1 In alphabetical order by name
db.stu.find().sort({"name":1})
#2 In reverse order by age and in positive order by ID
db.stu.find().sort({"age":"-1","_id":"1"})
#3. Count the total ages of boys and girlsDb. Stu. Aggregate ([{$group: {_id: "$sex", "total age" : {$sum: "$age"}}}])
#4. Find the total number of students and the average age
db.stu.aggregate([
{
$group:{
_id: null,
total_num: {$sum:1},
total_avg: {$avg: "$age"}
}
}
])
#5. Query the number of male students and female students in ascending orderDb. Stu. Aggregate ([{$group: {_id: "$sex", "total" : {$sum: 1}}}, {$sort: {" total ": 1}}])Copy the code