1. Conditional operator
The conditional operator is used to compare two expressions and get data from the mongodb collection.
The condition operators in mongodb are:
(>) greater than - $GT
(< less than - $LT
(> =) greater than or equal to - $GTE
(< =) less than or equal to - $LTE
Clear set data
db.col.remove({})
Insert the following data
> db.col.insert({
Title: 'test data 200',
Description: 'attention to the official account, Ronaldinho's technical notes, focuses on developing technology research and knowledge sharing',
By: 'Xiao Luo's technical notes',
url: 'http://www.yuwowugua.com',
tags: ['test'],
likes: 200
})
> db.col.insert({
Title: 'test data 150',
Description: 'attention to the official account, Ronaldinho's technical notes, focuses on developing technology research and knowledge sharing',
By: 'Xiao Luo's technical notes',
url: 'http://www.yuwowugua.com',
tags: ['test'],
likes: 150
})
> db.col.insert({
Title: 'test data 100',
Description: 'attention to the official account, Ronaldinho's technical notes, focuses on developing technology research and knowledge sharing',
By: 'Xiao Luo's technical notes',
url: 'http://www.yuwowugua.com',
tags: ['test'],
likes: 100
})
Use the find() command to view the data:
> db.col.find()
{"_id": ObjectId ("5a6a083598891b4abe9cc8cc"), "title": "test data 200", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 200}
{"_id": ObjectId ("5a6a083e98891b4abe9cc8cd"), "title": "test data 150", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 150}
{"_id": ObjectId ("5a6a084498891b4abe9cc8ce"), "title": "test data 100", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 100}
1.1 (>) greater than operator – $GT
db.col.find({"likes" : {$gt : 100}})
Similar to SQL statement:
select * from col where likes > 100;
Output result
{"_id": ObjectId ("5a6a083598891b4abe9cc8cc"), "title": "test data 200", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 200}
{"_id": ObjectId ("5a6a083e98891b4abe9cc8cd"), "title": "test data 150", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 150}
1.2 (> =) greater than or equal to operator – $GTE
If you want to get data with “likes” greater than or equal to 100 in the “col” set, you can use the following command:
db.col.find({likes : {$gte : 100}})
Similar to SQL statement:
select * from col where likes >=100;
Output results:
{"_id": ObjectId ("5a6a083598891b4abe9cc8cc"), "title": "test data 200", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 200}
{"_id": ObjectId ("5a6a083e98891b4abe9cc8cd"), "title": "test data 150", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 150}
{"_id": ObjectId ("5a6a084498891b4abe9cc8ce"), "title": "test data 100", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 100}
1.3 (< less than operator – $LT
If you want to get data with “likes” less than 150 in the “col” set, you can use the following command:
db.col.find({likes : {$lt : 150}})
Similar to SQL statement:
select * from col where likes < 150;
Output results:
> db.col.find({likes : {$lt : 150}})
{"_id": ObjectId ("5a6a084498891b4abe9cc8ce"), "title": "test data 100", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 100}
1.4 (< =) less than operator – $LTE
If you want to get data with “likes” less than or equal to 150 in the “col” set, you can use the following command
db.col.find({likes : {$lte : 150}})
Similar to SQL statement:
select * from col where likes <= 150;
Output results:
> db.col.find({likes : {$lte : 150}})
{"_id": ObjectId ("5a6a083e98891b4abe9cc8cd"), "title": "test data 150", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 150}
{"_id": ObjectId ("5a6a084498891b4abe9cc8ce"), "title": "test data 100", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 100}
1.5 using (< and (> queries – LT and GT
If you want to get data with “likes” greater than 100 and less than 200 in the “col” set, you can use the following command:
db.col.find({likes : {$lt :200, $gt : 100}})
Similar to SQL statement:
select * from col where likes>100 AND likes<200;
Output results:
> db.col.find({likes : {$lt :200, $gt : 100}})
{"_id": ObjectId ("5a6a083e98891b4abe9cc8cd"), "title": "test data 150", "description": "pay attention to the official account, Ronaldinho technical notes, focus on the development of technology research and knowledge sharing", "by": "Ronaldinho technical notes", "URL": "http://www.yuwowugua.com", "tags": [test], "likes": 150}
Some abbreviations:
$gt -------- greater than >
$gte --------- gt equal >=
$lt -------- less than <
$lte --------- lt equal <=
$ne ----------- not equal !=
$eq -------- equal =
2. Limit and skip methods
Mongodb limit() method
If you need to read a specified number of data records in mongodb, you can use mongodb’s limit method. The limit () method accepts a number parameter, which specifies the number of records read from mongodb.
Insert test data
db.col.insert({title: 'MongoDB-1'})
db.col.insert({title: 'MongoDB-2'})
db.col.insert({title: 'MongoDB-3'})
db.col.insert({title: 'MongoDB-4'})
MongoDB Enterprise > db.col.find()
{ "_id" : ObjectId("5a6e8eaef14a3f270ba2dd0c"), "title" : "MongoDB-1" }
{ "_id" : ObjectId("5a6e8ec8f14a3f270ba2dd0d"), "title" : "MongoDB-2" }
{ "_id" : ObjectId("5a6e8ecbf14a3f270ba2dd0e"), "title" : "MongoDB-3" }
{ "_id" : ObjectId("5a6e8ed5f14a3f270ba2dd0f"), "title" : "MongoDB-4" }
MongoDB Enterprise >
The basic syntax of the limit() method is as follows:
> db.COLLECTION_NAME.find().limit(NUMBER)
The above example shows two records in the query document:
MongoDB Enterprise > db.col.find().limit(2)
{ "_id" : ObjectId("5a6e8eaef14a3f270ba2dd0c"), "title" : "MongoDB-1" }
{ "_id" : ObjectId("5a6e8ec8f14a3f270ba2dd0d"), "title" : "MongoDB-2" }
MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).limit(2)
{ "title" : "MongoDB-1" }
{ "title" : "MongoDB-2" }
MongoDB Enterprise >
Note: if you do not specify the parameters in the limit () method, all the data in the collection will be displayed.
MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).limit()
{ "title" : "MongoDB-1" }
{ "title" : "MongoDB-2" }
{ "title" : "MongoDB-3" }
{ "title" : "MongoDB-4" }
Skip () method
In addition to using the limit () method to read the specified number of data, we can also use the skip () method to skip the specified number of data. The skip method also accepts a number parameter as the number of records to skip.
The syntax format of the skip() method script is as follows:
> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Example
The above example only displays the second document data
MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).limit(1).skip(1)
{ "title" : "MongoDB-2" }
MongoDB Enterprise >
Note: the default parameter of skip() method is 0
3, sort
In mongodb, sort() method is used to sort data. Sort() method can specify the sorted fields by parameters
Use 1 and – 1 to specify how to sort, where 1 is ascending and – 1 is descending.
The basic syntax of the sort() method is as follows:
> db.COLLECTION_NAME.find().sort({KEY:1})
The data in the col set is as follows:
MongoDB Enterprise > db.col.find()
{ "_id" : ObjectId("5a6e8eaef14a3f270ba2dd0c"), "title" : "MongoDB-1" }
{ "_id" : ObjectId("5a6e8ec8f14a3f270ba2dd0d"), "title" : "MongoDB-2" }
{ "_id" : ObjectId("5a6e8ecbf14a3f270ba2dd0e"), "title" : "MongoDB-3" }
{ "_id" : ObjectId("5a6e8ed5f14a3f270ba2dd0f"), "title" : "MongoDB-4" }
MongoDB Enterprise >
Where 1 is in ascending order and – 1 is for descending order
The following example demonstrates the descending order of data in the col set by field Title:
MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).sort({"title":-1})
{ "title" : "MongoDB-4" }
{ "title" : "MongoDB-3" }
{ "title" : "MongoDB-2" }
{ "title" : "MongoDB-1" }
MongoDB Enterprise >
Note: if the sort () method is not specified, the documents are sorted in ascending order by default.
4. Index
Index usually can greatly improve the efficiency of query. If there is no index, mongodb must scan every file in the collection and select the records that meet the query criteria when reading data.
This kind of scan full set query efficiency is very low, especially when dealing with a large number of data, the query can take tens of seconds or even minutes, which is very fatal to the performance of the website.
Index is a special data structure, which is stored in a set of data that is easy to traverse and read. Index is a structure that sorts the values of one or more columns in a database table
Mongodb uses the ensureindex() method to create the index. The basic syntax format of the ensureindex() method is as follows:
> db.COLLECTION_NAME.ensureIndex({KEY:1})
In the syntax, the key value is the index field you want to create, 1 is to specify to create the index in ascending order, if you want to create the index in descending order, specify – 1.
> db.COLLECTION_NAME.ensureIndex({KEY:1})
In the syntax, the key value is the index field you want to create, 1 is to specify to create the index in ascending order, if you want to create the index in descending order, specify – 1.
MongoDB Enterprise > db.col.ensureIndex({"title":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
MongoDB Enterprise >
DB. Col. insert ({Title: 'mongodb tutorial',
Description: 'mongodb is a NoSQL database',
By: 'Search Cloud Library Tutorial - focus on research and knowledge sharing of development technology',
url: 'http://www.souyunku.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})
In the ensureindex () method, you can also set to use multiple fields to create an index (called a composite index in a relational database).
MongoDB Enterprise > db.col.ensureIndex({"title":1,"description":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 4,
"ok" : 1
}
Ensureindex() receives optional parameters. The list of optional parameters is as follows:
To create an index in the background:
The index building process will block other database operations. Background can specify the background mode to create the index, that is, add the “background” optional parameter. The default value of “background” is false.
MongoDB Enterprise > db.col.ensureIndex({"url":1}, {background: true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 5,
"numIndexesAfter" : 6,
"ok" : 1
}
MongoDB Enterprise >
4. Polymerization
Aggregation in mongodb is mainly used to process data (such as statistical average, sum, etc.) and return the calculated data results. It is similar to count (*) in SQL statement.
Aggregate () method
Delete previous test data
MongoDB Enterprise > db.col.remove({})
WriteResult({ "nRemoved" : 5 })
MongoDB Enterprise >
Insert new test data
db.col.insert({
Title: 'mongodb tutorial',
Description: 'mongodb is a NoSQL database',
By user: 'Xiao Luo',
url: 'http://www.yuwowugua.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})
db.col.insert({
Title: 'mongodb tutorial',
Description: 'mongodb is a NoSQL database',
By user: 'Xiao Luo',
url: 'http://www.yuwowugua.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 200
})
db.col.insert({
Title: 'mongodb tutorial',
Description: 'mongodb is a NoSQL database',
By user: 'Xiao Luo',
url: 'http://www.yuwowugua.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 300
})
MongoDB Enterprise > db.col.find()
{"_id": objectid ("5a6ebfab5326a260464a4072"), "title": "mongodb tutorial", "description": "mongodb is a NoSQL database", "by user": "Xiao Luo", "URL": "http://www.yuwowugua.com", "tags": ["mongodb", "database", "NoSQL"], "likes": 100}
{"_id": objectid ("5a6ebfab5326a260464a4073"), "title": "mongodb tutorial", "description": "mongodb is a NoSQL database", "by user": "Xiao Luo", "URL": "http://www.yuwowugua.com", "tags": ["mongodb", "database", "NoSQL"], "likes": 200}
{"_id": objectid ("5a6ebfab5326a260464a4074"), "title": "mongodb tutorial", "description": "mongodb is a NoSQL database", "by user": "Xiao Luo", "URL": "http://www.yuwowugua.com", "tags": ["mongodb", "database", "NoSQL"], "likes": 300}
MongoDB Enterprise >
The aggregation method in mongodb uses aggregate(). The basic syntax format is as follows:
> db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
MongoDB Enterprise > db.col.aggregate([{$group : {_id : "$by_user", num_tutorials : {$sum : 1}}}])
{
"Ou ID": "Xiao Luo",
"num_tutorials": 3
}
MongoDB Enterprise > db.col.aggregate([{$group : {_id : "$by_user", totle : {$sum : 1}}}])
{
"Ou ID": "Xiao Luo",
"totle": 3
}
MongoDB Enterprise >
The above example is similar to SQL statement:
select by_user, count(*) from col group by by_user
In the above example, we group the data through the by user field and calculate the sum of the same values of the by user field.
The following table shows some aggregate expressions:
Concept of pipeline
Pipes are commonly used in UNIX and Linux to take the output of the current command as a parameter to the next command.
The aggregation pipeline of mongodb will pass the results of mongodb documents to the next pipeline after one pipeline is processed. Pipeline operations are repeatable.
Expression: processes the input document and outputs it. The expression is stateless and can only be used to calculate the documents of the current aggregation pipeline, and cannot process other documents.
Here we introduce some common operations in the aggregation framework:
$project: modify the structure of the input document. It can be used to rename, add, or delete fields, or to create calculation results and nested documents.
Match: used to filter data and only output documents that meet the conditions.
Match uses mongodb’s standard query operations.
$limit: used to limit the number of documents returned by the mongodb aggregation pipeline.
$skip: skips the specified number of documents in the aggregation pipeline and returns the remaining documents.
$unwind: split an array type field in the document into multiple fields, each containing a value in the array.
$group: Group documents in the collection, which can be used for statistics.
$sort: sort the input documents and output them.
$geonear: output ordered documents close to a geographic location.
Pipe operator instance
1. $project instance
MongoDB Enterprise > db.col.aggregate(
{ $project : {
title : 1 ,
by_user : 1 ,
}}
);
{"_id": objectid ("5a6ebfab5326a260464a4072"), "title": "mongodb tutorial", "by" user ":" Xiaoluo "}
{"_id": objectid ("5a6ebfab5326a260464a4073"), "title": "mongodb tutorial", "by" user ":" Xiaoluo "}
{"_id": objectid ("5a6ebfab5326a260464a4074"), "title": "mongodb tutorial", "by" user ":" Xiaoluo "}
MongoDB Enterprise >
In this way, there are only three fields in the result: ID, Tilte and by user. By default, the ID field is included. If you want to exclude ID, you can do this:
MongoDB Enterprise > db.col.aggregate(
{ $project : {
_id : 0 ,
title : 1 ,
by_user : 1
}});
{"title": "mongodb tutorial", "by" user ":" Xiaoluo "}
{"title": "mongodb tutorial", "by" user ":" Xiaoluo "}
{"title": "mongodb tutorial", "by" user ":" Xiaoluo "}
2. $match instance
db.col.aggregate( [
{ $match : { likes : { $gt : 90, $lte : 200 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );
Match is used to get records with likes greater than 70 but less than or equal to 90, and then send the qualified records to the next stage
Group pipeline operator.
MongoDB Enterprise > db.col.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "penglei", "num_tutorial" : 3 }
MongoDB Enterprise >
The above example is similar to SQL statement:
select by_user as _id, count(*) as num_tutorial from mycol group by by_user
Aggregate operations by day, month, year, week, hour and minute are as follows:
db.getCollection('m_msg_tb').aggregate(
[
{$match:{m_id:10001,mark_time:{$gt:new Date(2017,8,0)}}},
{$group: {
_id: {$dayOfMonth:'$mark_time'},
pv: {$sum: 1}
}
},
{$sort: {"_id": 1}}
])
The time keywords are as follows:
$dayofyear: returns the day of the year (366 days of the year).
$dayofmonth: returns the day of the month (1 to 31).
$DayOfWeek: returns the day of the week (1: Sunday, 7: Saturday).
$year: returns the year part of the date.
$month: returns the month part of the date (1 to 12).
$week: returns the week ordinal of the year (0 to 53).
$hour: returns the hour part of the date.
$minute: returns the minute part of the date.
$second: returns the second part of the date (the second part of the date is returned as a number between 0 and 59, but it can be 60 to calculate leap seconds).
$millisecond: returns the millisecond part of the date (0 to 999).
$dateToString: { $dateToString: { format: , date: } }。