MongoDB Related methods

Source: Internet
Author: User
Tags createindex mongodb

First, MongoDB sortMongoDB sort () method

Using the sort () method in MongoDB to sort the data, the sort () method can specify the sorted fields by parameter and use 1 and-one to specify how the sort is sorted, where 1 is in ascending order, and 1 is used for descending order.

Grammar

The basic syntax for the sort () method is as follows:

>db. Collection_name.find (). Sort ({key:1})
Instance

The data in the Col collection is as follows:

{"_id": ObjectId ("5b554b9e7dc80c93e5d47b3a"), "title": "Study1", "description": "MongoDB Study", "by": "Cara1", "url" : "http://cara.com", "tags": ["MongoDB", "Database", "NoSQL"], "likes": 200}
{"_id": ObjectId ("5b554bc37dc80c93e5d47b3b"), "title": "Study2", "description": "MongoDB Study", "by": "Cara2", "url" : "http://cara.com", "tags": ["MongoDB", "Database", "NoSQL"], "likes": 150}
{"_id": ObjectId ("5b554bd47dc80c93e5d47b3c"), "title": "Study3", "description": "MongoDB Study", "by": "Cara3", "url" : "http://cara.com", "tags": ["MongoDB", "Database", "NoSQL"], "likes": 100}

The following example shows that the data in the Col collection is sorted in descending order by field likes:

> db.col.find ({},{"title": 1,_id:0}). Sort ({"Likes":-1})
{"title": "Study1"}
{"title": "Study2"}
{"title": "Study3"}

Second, MongoDB index

Indexes can often greatly improve the efficiency of queries, and if there is no index, MongoDB must scan every file in the collection and select those records that meet the query criteria 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 fatal 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

CreateIndex () method

MongoDB uses the CreateIndex () method to create an index.

Note that the index method was created before the 3.0.0 version Db.collection.ensureIndex (), and the later version uses the Db.collection.createIndex () method, Ensureindex () is also available, but only The alias of the CreateIndex ().

Grammar

The basic syntax format for the CreateIndex () method is as follows:

>db.collection.createindex (keys, options)

The Key value in the syntax is the index field you want to create, 1 for the specified index in ascending order, or 1 if you want to create the index in descending order.

Instance

> Db.col.createIndex ({"title": 1})

In the CreateIndex () method, you can also set up to create indexes using multiple fields (called Composite indexes in relational databases).

>db.col.createindex ({"title": 1, "description": -1}) >

CreateIndex () receives optional parameters, the optional parameter list is as follows:

Parameter Type Description
Background Boolean The indexing process blocks other database operations, and background can specify a later way to create an index, which is to add "background" optional parameters. The default value for "Background" is false.
Unique Boolean Whether the established index is unique. Specifies true to create a unique index. The default value is false.
Name String The name of the index. If not specified, MongoDB generates an index name by the field name and sort order of the connection index.
Dropdups Boolean Whether to delete duplicate records when establishing a unique index, specifying true to create a unique index. The default value is false.
Sparse Boolean Do not enable indexing for 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.
Expireafterseconds Integer Specify a value in seconds, complete the TTL setting, and set the lifetime of the collection.
V Index version The version number of the index. The default index version depends on the version that is run when the index is mongod created.
Weights Document The index weight value, which is between 1 and 99,999, that represents the score weight of the index relative to the other indexed fields.
Default_language String For a text index, this parameter determines the list of rules for the stop word and the stemming and the word changer. Default to English
Language_override String For a text index, this parameter specifies the name of the field contained in the document, the language overrides the default language, and the default value is language.


Instance

To create an index in the background:

Db.values.createIndex ({open:1, close:1}, {background:true})

Make the creation work in the background by adding the background:true option when creating the index


third, MongoDB aggregation

MongoDB Aggregation (aggregate) is primarily used to process data (such as statistical averages, sums, etc.) and returns 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)
Instance

The data in the collection is as follows:

> Db.col.find (). Pretty ()
{
"_id": ObjectId ("5b554b9e7dc80c93e5d47b3a"),
"title": "Study1",
"description": "MongoDB Study",
"By": "Cara1",
"url": "Http://cara.com",
"Tags": [
"MongoDB",
"Database",
"NoSQL"
],
"Likes": 200
}
{
"_id": ObjectId ("5b554bc37dc80c93e5d47b3b"),
"title": "Study2",
"description": "MongoDB Study",
"By": "Cara2",
"url": "Http://cara.com",
"Tags": [
"MongoDB",
"Database",
"NoSQL"
],
"Likes": 150
}
{
"_id": ObjectId ("5b554bd47dc80c93e5d47b3c"),
"title": "Study3",
"description": "MongoDB Study",
"By": "Cara3",
"url": "Http://cara.com",
"Tags": [
"MongoDB",
"Database",
"NoSQL"
],
"Likes": 100
}
>

Now we calculate the number of articles written by each author through the above set, using aggregate () to calculate the results as follows:


> db.col.aggregate ([{$group: {_id: "$by", Num_tutorial: {$sum: 1}}])
{"_id": "Cara3", "Num_tutorial": 1}
{"_id": "Cara2", "Num_tutorial": 1}
{"_id": "Cara1", "Num_tutorial": 1}
>

The above example resembles an SQL statement: Select By_user, COUNT (*) from MyCol GROUP by By_user

In the example above, we group the data through the Field By_user field and calculate the sum of the same values in the By_user field.


The following table shows some of the aggregated expressions:

An expression Description Example
$sum Calculates the 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"}}])
$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 Inserts a value 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 documents. Db.mycol.aggregate ([{$group: {_id: "$by _user", First_url: {$first: "$url"}}])
$last Get the last document data based on the ordering of the resource documents Db.mycol.aggregate ([{$group: {_id: "$by _user", Last_url: {$last: "$url"}}])




MongoDB Related methods

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.