MongoDB notes (MongoDB $type operator, limit and skip methods, sort () method, index, aggregation (aggregate))

Source: Internet
Author: User
Tags data structures numeric min mongodb mongodb limit regular expression

<\?php
/**
* MongoDB $type operator
*/

/**
* The $type operator is based on the Bson type to retrieve the matching data type in the collection and returns the result.
* The types of MongoDB that can be used are shown in the following table:
* Type Number Notes
* Double 1
* String 2
* Object 3
* Array 4
* Binary Data 5
* Undefined 6 is obsolete.
* Object ID 7
* Boolean 8
* Date 9
* Null 10
* Regular Expression 11
* JavaScript 13
* Symbol 14
* JavaScript (with scope) 15
* 32-bit Integer 16
* Timestamp 17
* 64-bit Integer 18
* Min key 255 Query with-1.
* Max Key 127
*/

/**
* MongoDB operator-$type instance
* If you want to get the data in the "Col" collection with the title String, you can use the following command:
* Db.col.find ({"title": {$type: 2}})
*/

/****************************************************************************************************** /
/********************************************************************************************************** ***/

/**
* MongoDB Limit and Skip method
*/

/**
* Limit
*/

/**
* MongoDB Limit () method
* If you need to read a specified number of data records in MongoDB, you can use the MongoDB limit method,
The * Limit () method takes a numeric parameter that specifies the number of record bars read from MongoDB.
* Grammar
* The basic syntax of the limit () method is as follows:
* >db. Collection_name.find (). Limit (number)
*/

/**
* SKIP ()
*/

/**
* MongoDB Skip () method
* In addition to using the limit () method to read a specified amount of data, we can also use the Skip () method to skip a specified amount of data.
* The Skip method also accepts a numeric parameter as the number of skipped record bars.
*/

/**
* Notes List
*/

/**
* Db.col.find ({},{"title": 1,_id:0}). Limit (2)
* Additional notes:
* The first {} puts a where condition, and a null representation returns all documents in the collection.
* The second {} Specifies that those columns are displayed and not displayed (0 means that 1 is not displayed).
* To read 100 records from 10 records, equivalent to limit (10,100) in SQL.
* > DB. Collection_name.find (). Skip. Limit (100)
* The above example skips the previous 10 bars in the collection to return 100 data.
* Skip and limit combine to achieve paging.
* When querying with sort,skip,limit, regardless of position, first execution order sort and then skip again limit.
*/

/**
* Supplementary Instructions
*/

/**
* added that the skip and limit methods are only suitable for small data volume paging, if the millions efficiency will be very low, because the Skip method is a number of data in the past, it is recommended to use Where_limit
* After reviewing some of the information, we found that all the information is said:
* Do not easily use skip to make queries, otherwise the large amount of data will lead to a sharp decline in performance, this is because skip is a number of one, more natural slow.
* So skip is going to be avoided, so how to avoid it. First of all, the paper reviews the post-timestamp paging scheme of SQL paging, which uses the ordered nature of the fields, and uses the query to fetch the data.
* You can avoid a large number of numbers directly. In other words, if it comes with such a condition, the query will be more efficient, in fact it is. Let's check it out:
*/
/**
* B.test.sort ({"Amount": 1}). Skip (100000). Limit (Ten)//183ms
* Db.test.find ({amount:{$gt: 2399927}). Sort ({"Amount": 1}). Limit (Ten)//53ms
*/

/********************************************************************************************************** ****/
/********************************************************************************************************** ***/

/**
* MongoDB Sort
* MongoDB Sort () method
*/

/**
* Using the sort () method to sort data in MongoDB, the sort () method can specify the sorted field by parameter,
* and use 1 and-to specify how to sort,
* Where 1 is in ascending order,
* and-1 is used in descending order.
* Grammar
The basic syntax for the sort () method is as follows:
* >db. Collection_name.find (). Sort ({key:1})
*/

/**
Notes
* Skip (), Limilt (), sort () three when executed together, the order of execution is first sort (), then Skip (), and finally the limit () shown.
*/

/********************************************************************************************************** ***/
/********************************************************************************************************** ***/

/**
*mongodb Index
*/

/**
Introduction
* Indexes can often greatly improve the efficiency of queries, and if there is no index, MongoDB must scan each file in the collection and select those that meet the criteria of the query when reading the data.
* This scan full set of query efficiency is very low, especially in the processing of large amounts of data, the query can take dozens of seconds or even a few minutes, which is very deadly to the performance of the site.
* Indexes are special data structures that are stored in an easy-to-traverse collection of data that is a structure for sorting the values of one or more columns in a database table
*/

/**
* Ensureindex () method
* MongoDB uses the Ensureindex () method to create an index.
*/

/**
* Grammar
* The basic syntax format for the Ensureindex () method is as follows:
* >db. Collection_name.ensureindex ({key:1})
* Syntax The Key value is the index field you want to create, 1 for the specified index in ascending order, if you want to create an index in descending order specified as-1.
*/

/**
* Instance
* >db.col.ensureindex ({"title": 1})
* >
* composite Index
* Ensureindex () method you can also set to create using multiple fields An index (called a composite index in a relational database).
* >db.col.ensureindex ({"title": 1, "description": -1})
* >
*/

/**
* ENSUREINDEX () receives optional parameters, and the optional parameter list is as follows:
* Parameter Type Description
* Background The Boolean indexing process blocks other database operations, b Ackground can specify the future way to create the index, that is, add "background" optional parameters. The default value for "background" is false. The
* Unique Boolean index that is established is unique. Specifies true to create a unique index. The default value is False. The name of the
* Name string index. If not specified, MongoDB generates an index name by the field name and sort order of the connection index.
* dropdups Boolean to delete duplicate records when establishing a unique index, specifying true to create a unique index. The default value is False.
* Sparse Boolean does not enable indexing of field data that does not exist in the document; This parameter requires special attention, and if set to true, documents that do not contain corresponding fields are not queried in the index field ... The default value is False. The
* expireafterseconds integer specifies a value in seconds, which completes the TTL setting and sets the lifetime of the collection. The version number of the
* V index version. The default index version depends on the version that is run when the index is mongod created. The
* Weights Document Index weight value, which is between 1 and 99,999, represents the score weight of the index relative to other indexed fields.
* Default_language string for the text index, which determines the list of rules for the stop word and the stemming and the word changer. The default is English
* language_override string for the text index, which specifies the name of the field contained in the document, the language overrides the default language, and the default value is language.
*/

/**
* Example
* Create an index in the background:
* Db.values.ensureIndex ({open:1, close:1}, {background:true})
* Make the creation work in the background by adding the background:true option when creating the index
*/

/********************************************************************************************************** ***/
/********************************************************************************************************** ***/

/**
* MongoDB Aggregation
*/

/**
* MongoDB Aggregation (aggregate) is primarily used to process data (such as statistical averages, sums, etc.) and return the computed data results. A bit like the count (*) in the SQL statement.
*/

/**
* Aggregate () method
*/

/**
* The method of aggregation in MongoDB uses aggregate ().
* Grammar
The basic syntax format for the * aggregate () method is as follows:
* >db. Collection_name.aggregate (aggregate_operation)
*/

/**
* Now we calculate the number of articles written by each author through the collection above, using aggregate () to calculate the results as follows:
* > Db.mycol.aggregate ([{$group: {_id: "$by _user", num _tutorial: {$sum: 1}}])
* {
* "result": [
* {
* "_id": "runoob.com",
* "num_tutorial": 2 *},
* {
* "_id": "neo4j",
* "num_tutorial": 1
*}
*],
* "OK": 1
*}
* >
* Above instance similar to SQL statement: Select By_user, COUNT (*) from MyCol GROUP BY By_user
*/

/**
* The following table shows some of the aggregated expressions:
* Expression Description Instance
* $sum calculate sum. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$sum: "$likes"}}])
* $avg calculate average db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$avg: "$likes"}}]) The
* $min gets the minimum value that corresponds to all documents in the collection. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$min: "$likes"}}])
* $max Gets the maximum value that corresponds to all documents in the collection. Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$max: "$likes"}}])
* $push Insert values into an array in the resulting document. Db.mycol.aggregate ([{$group: {_id: ' $by _user ', url: {$push: ' $url '}}])
* $addToSet Inserts a value into an array in the resulting document, but does not create a copy. Db.mycol.aggregate ([{$group: {_id: "$by _user", url: {$addToSet: "$url"}}])
* $first Gets the first document data based on the ordering of the resource document. Db.mycol.aggregate ([{$group: {_id: "$by _user", First_url: {$first: "$url"}}])
* $last Gets the last document data based on the ordering of the resource documents DB.MYC Ol.aggregate ([{$group: {_id: "$by _user", Last_url: {$last: "$url"}}])
*/

/**
* Concept of piping
* Pipelines are typically used in UNIX and Linux to use the output of the current command as a parameter to the next command.
*/

/**
* MongoDB's aggregation pipeline passes the MongoDB document to the next pipeline processing after a pipeline has finished processing. Pipeline operations can be repeated.
*/

/**
* Here's a look at some of the things that are commonly used in the aggregation framework:
* $project: Modifies the structure of the input document. You can use it to rename, add, or delete fields, or to create calculations and nested documents.
* $match: Used to filter data and only output documents that match the criteria. $match a standard query operation using MONGODB.
* $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: Splits one of the array type fields in the document into multiple bars, each containing one of the values in the array.
* $group: Groups The documents in the collection to be used for statistical results.
* $sort: The output is sorted after the input document.
* $geoNear: Outputs an ordered document close to a geographic location.
*/

/**
* Examples of pipe operators
*/

/**
* 1, $project examples
* Db.article.aggregate (
* {$project: {
* Title:1, # 1 means ascending-1 means descending meaning
* Author:1,
* }}
* ); So there are only _id,tilte and author three fields in the result, by default the _id field is included, if you want to not include _id, you can: Db.article.aggregate ({$project: {_id:0, title:1 , author:1}});
*/

/**
* 2. $match instance Db.articles.aggregate ([{$match: {score: {$gt: $, $lte: +}}}, {$group: {_id:null, count: {$s Um:1}}}

] );

$match is used to get a score greater than 70 less than or equal to 90 records, and then the qualifying record is sent to the next stage of the $group pipeline operator for processing.
*/

/**
* 3. $skip Example
* Db.article.aggregate (
* {$skip: 5});
* After the $skip pipeline operator, the first five documents are "filtered" out.
*/

/**
* Notes List
*/

/**
* Db.mycol.aggregate ([{$group: {_id: "$by _user", num_tutorial: {$sum: 1}}])
* The above examples are similar to SQL statements:
* Select By_user as _id, COUNT (*) as num_tutorial from MyCol Group by By_user
*/

/**
* Aggregated by day, month, year, week, hour, per minute, 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 keyword is as follows:
* $dayOfYear: Returns this date is the day of the year (366 days of the year).
* $dayOfMonth: Return This date is the day of the one months (1 to 31).
* $dayOfWeek: Returns the week of the week (1: Sunday, 7: Saturday).
* $year: Returns the year portion of the date.
* $month: Returns the month portion of the date (1 to 12).
* $week: Returns the number of weeks (0 to 53) of the year in which the date is located.
* $hour: Returns the hour portion of the date.
* $minute: Returns the minute part of the date.
* $second: Returns the second part of the date, in the form of a number from 0 to 59, that returns the secondary part of the date, but can be 60来 to calculate leap seconds.
* $millisecond: Returns the millisecond portion of the date (0 to 999).
* $dateToString: {$dateToString: {format:, Date:}}.
*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.