MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications.
1. Introduction
There’s been a debate ever since the front and back end split, where does the front end split, is the front end just writing pages? Do you need to learn about servers, databases, and other back ends?
I think it is very necessary to explain the existence of the browser indexedDB if the front and back ends are separated by browser and server. Existence is reasonable, and the more you know, the further you can go.
The company recently had a demand for Mongo aggregation, and I was suddenly greatly interested in it. This article is mongo’s learning and problem solving notes.
2. Environmental
Environmental installation is not relevant to this article, but provides several channels:
- Along with the
mongo
Official documentation to install, local start debugging; mongo
The client,Robo 3TVery easy to use oh;mongo
The officialCommand line small window(No installation direct use, learning recommendations).
Introduced 3.
There are several schools (DB) in the city. Let’s take a look at the schools in the city
Then you need to specify the school that you can manipulate (mongo defaults to test).
4. Insert the
The final exam came and the results were as follows:
The name | gender | Chinese language and literature | mathematics | English | Test time |
---|---|---|---|---|---|
The little one | The boy | 90 | 90 | 90 | June 10, 2019 |
Small 2 | The girl | 80 | 80 | 80 | June 10, 2019 |
Small three | The girl | 70 | 70 | 70 | June 10, 2019 |
Small four | The girl | 60 | 60 | 60 | June 12, 2019 |
When the grades come out, the teacher enters them into the grade system.
// insertOne inserts a piece of data
db.student.insertOne({
name: "Little one".sex: 'the boys'.chinese: '90'.math: '90'.english: '90'.createdAt: new Date('2016-06-09T16:00:00Z')})Copy the code
Note: New Date(‘2016-06-09T16:00:00Z’) is universal standard time, and mongo is also universal standard time. China is in the 8th East zone, plus 8 hours, which translates to June 10, 2019.
The teacher thought it was too boring to add them one by one, so he added them all at once:
// // Insert method: insertMany Inserts a piece of data
db.student.insertMany([
{ name: "Small 2".sex: 'the girl'.chinese: '80'.math: '80'.english: '80'.createdAt: new Date('2016-06-09T16:00:00Z')},
{ name: "Little three".sex: 'the girl'.chinese: '70'.math: '70'.english: '70'.createdAt: new Date('2016-06-09T16:00:00Z')},
{ name: "Small four.".sex: 'the girl'.chinese: '60'.math: '60'.english: '60'.createdAt: new Date('2016-06-11T16:00:00Z')})Copy the code
- School (
db
) : database,mongo
Can hold multiple databases, used by defaulttest
;- Student Collection (
student
(a class of all the students.- Student Information (
data
) : documents, which can be understood as individual student information.
5. Modify
The teacher discovers suddenly, small three is female dress big guy actually, the teacher is cheated become angry from embarrassment, modify its gender then.
// Update method: updateOne
db.student.updateOne(
{ name: 'small three' },
{ $set: { sex: 'Women's Wear'}})Copy the code
Where $set is the update operator that tells Mongo what to do with the data that matches. The usage is similar, listing as follows (more update operators) :
- $currentDate: set time;
- $inc: increments the value of a field by the specified amount;
- $min: Updates a field only if the specified value is less than the value of an existing field;
- $Max: Updates a field only if the specified value is greater than the value of an existing field;
- $mul: Multiplies the value of the field by the specified amount;
- $rename: Rename a field;
- $set: Sets the value of a field in the document;
- $setOnInsert: Sets the value of the field if the update results in document inserts. Update operations that modify existing documents have no impact;
- $unset: Removes the specified field from the document.
6. Look for
All three students studied hard. After the final exam, Xiao Yi was confident that he could get the first prize, so xiao Yi went to check his grades.
// Query method: find
// The pretty method makes the data look better
db.student.find({name: 'a little'}).pretty()
Copy the code
Then check the grades of primary two and primary three. He suddenly found that the small woman is a woman of the fact, shocked!
// Query method: find
db.student.find({$or: [{name: 'small 2'}, {name: 'small three'}]}).pretty()
Copy the code
Where $or is the query operator that tells Mongo what to do with the data that matches. The usage is similar, with the following enumeration (more query operators) :
- $eq: matches a value equal to the specified value;
- $gt: matches a value greater than the specified value;
- $lt: Matches values less than the specified value;
- $and: the enumeration conditions match;
- $not: none of the enumeration conditions match;
- $or: Enumerates conditions that match one of them.
7. Remove
Small one heart entanglement, finally tell this matter small three. Small three feel no face to classmates and teachers, decided to drop out. The teacher deleted xiao SAN’s information from the educational administration system.
// Delete method: deleteOne
db.student.deleteOne({name: 'small three'})
Copy the code
8. Cycle
The teacher at the end of the semester made a summary of the work, and found that the score was entered into a string, which should be a number type, so the operation cycle changed.
// The traversal method is forEach
db.student.find().forEach(function(doc) {
doc.chinese = NumberInt(doc.chinese);
doc.math = NumberInt(doc.math);
doc.english = NumberInt(doc.english);
db.student.save(doc);
})
Copy the code
Number type: NumberInt Specifies the number type.
9. The aggregation
The final teacher needs to work out the average scores of Chinese, math and English for the class.
9.1 aggregate
// Aggregate method: aggregate
$Chinese, $math, and $English represent only document fields.
db.student.aggregate([
{
$group: {
_id: null.sumChinese: { $sum: '$chinese' },
avgChinese: { $avg: '$chinese' },
sumMath: { $sum: '$math' },
avgMath: { $avg: '$math' },
sumEnglish: { $sum: '$english' },
avgEnglish: { $avg: '$english' },
}
}
]).pretty()
Copy the code
$group = group (_id); if null = no group, select all data. Where $sum and $avg are aggregate operators that tell Mongo what to do with the data that matches. The usage is similar, with the following enumeration (more aggregate operators) :
- $sum: Returns the sum of each group (ignoring non-numeric values);
- $AVg: Returns the average of each group (ignoring non-numeric values);
- $Max: returns the highest expression value for each group;
- $min: returns the lowest expression value for each group;
- $gte: Returns true if the given value is greater than or equal to, false otherwise;
- $lte: Returns true if the given value is less than or equal to, false otherwise;
- $add: Add a number to return the sum, or add a number and date to return a new date;
- $year: Returns the year of the date as a number (for example, 2014);
- $month: the month in which the date is returned as a number between 1 and 12;
- $dayOfMonth: Returns the day of the month for the date as a number between 1 and 31.
The teacher found that the above calculation method is to calculate the scores of all students, but this time only needs to calculate the scores of June 10, 2019, modified as follows:
db.student.aggregate([
{
$match: {
createdAt: {
$gte: new Date('2016-06-09T16:00:00Z'),
$lte: new Date('2016-06-10T16:00:00Z'}},}, {$project: {
name: 1.sex: 1.chinese: 1.math: 1.english: 1.time: {$add: ['$createdAt'.8 * 60 * 60 * 1000]}}}, {$group: {
_id: {
year: {'$year': '$time'},
month: {'$month': '$time'},
day: {'$dayOfMonth': '$time'}},sumChinese: { $sum: '$chinese' },
avgChinese: { $avg: '$chinese' },
sumMath: { $sum: '$math' },
avgMath: { $avg: '$math' },
sumEnglish: { $sum: '$english' },
avgEnglish: { $avg: '$english' },
}
}
]).pretty()
Copy the code
The time field is used to display the real time in China. Its value is createedAt plus 8 hours. Because Mongo stores world Standard time by default, China is in zone 8 east, and it takes an additional 8 hours to display China time correctly.
$match
The filter operator, as the name implies, only data that meets the criteria is passed on;$project
: Modifies the operator of the returned data structure. 1 indicates display, no write or 0 indicates no display. (aggregate
The aggregate method takes array arguments because of the concept of pipes, simply saying that the result of the execution of the preceding command is the argument to the following command, as injquery
The dot concatenate of.
9.2 graphs
In addition to using the aggregation approach, you can also use the MapReduce approach to calculate.
Map-reduce is a calculation model. In simple terms, a large amount of work (data) is decomposed (Map) and executed, and then the results are combined into a final result (Reduce). The Map-reduce provided by MongoDB is flexible and useful for large-scale data analysis.
db.student.mapReduce(
function(){
emit(null.this);
},
function(key, values){
var reducedVal = {
sumChinese: 0.avgChinese: 0.sumMath: 0.avgMath: 0.sumEnglish: 0.avgEnglish: 0
};
for (var i = 0; i < values.length; i++) {
reducedVal.sumChinese += values[i].chinese;
reducedVal.sumMath += values[i].math;
reducedVal.sumEnglish += values[i].english;
}
reducedVal.avgChinese = reducedVal.sumChinese / values.length;
reducedVal.avgMath = reducedVal.sumMath / values.length;
reducedVal.avgEnglish = reducedVal.sumEnglish / values.length;
return reducedVal;
},
{
query: {createdAt: {$gte: new Date('2016-06-09T16:00:00Z'), $lte: new Date('2016-06-10T16:00:00Z')}},
out: 'sum'
}
).find().pretty()
Copy the code
mongo
- According to the
query
Filter out suitable data (equivalent to aggregationaggregate
的$match
), tomap
Function (mapReduce
The first parameter accepted); map
A function callemit
The function iterates through all the filter data, passing the grouping as the first argument. We pass without groupingnull
The second argument is the corresponding data, and we pass the complete data toreduce
Function (mapReduce
Accepted second argument);reduce
The function to receivemap
The passedkey
和values
The value (corresponds to the one aboveemit(null, this)
), we just need to iterate through the assembly according to our own requirements and return the assembled data.
10. Summary
Mongo is a lot of fun, and this article is just to document some of the scenarios where mongo is used in feature development, and the content of Mongo is much more than the scope of this article. If you are interested, please refer to the official documentation.