005.MongoDB index and aggregate

A MongoDB index

The index is usually able to greatly improve the efficiency of the query, if there is no index, MongoDB has to scan each file in the collection when reading data and select those records that match the query criteria.
This query scans the whole collection efficiency is very low, especially when dealing with large amounts of data, queries can take tens of seconds or even minutes, the performance of this site is very deadly.
Index is a special data structure, a set of index data stored in a read easily traversed, the index value is a structure of a database table in one or more columns to sort.

1.1 createIndex () method

MongoDB uses createIndex () method to create the index.
Syntax:
  1 > db.collection.createIndex(keys, options)
Parameter Description:
  • Key: key value index field you want to create;
  • options: options to create an index showing ascending, to -1 to create a descending index.
  1 [root@uhost ~]# mongo --host 172.24.9.225 --port 27017 -u useradmin -p useradmin
  2 > use mydb
  3 > db.age01.createIndex({age: 1})
  4 {
  5         "createdCollectionAutomatically" : false,
  6         "numIndexesBefore" : 1,
  7         "numIndexesAfter" : 2,
  8         "ok" : 1
  9 }
 
createIndex () method, you can create an index set (called a composite index relational database) using the plurality of fields.
  1 > db.age01.createIndex({age: 1, tel: -1})
  2 {
  3         "createdCollectionAutomatically" : false,
  4         "numIndexesBefore" : 2,
  5         "numIndexesAfter" : 3,
  6         "ok" : 1
  7 }
 

1.2 createIndex () optional parameters

Optional parameters are listed below:
Parameter
Type
Description
background
Boolean
Built indexing process will block other database operations, create an index table way after background can be specified, an increase of "background" optional parameters. "Background" default value is false.
unique
Boolean
The indexing is unique. Specifies to create a unique index to true. The default value is false.
name
string
Name of the index. If not specified, the field name and sort order MongoDB generated by a join index name index.
sparse
Boolean
Is not enabled for field data file does not exist in the index; this parameter requires special attention, if set to true, then the index field will not check out the document does not contain the corresponding field .. The default value is false.
expireAfterSeconds
integer
Specify a value in units of seconds, to complete the setting TTL to set the set time to live.
v
index version
索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
weights
document
索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。
default_language
string
对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
language_override
string
对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.
  1 > db.age01.createIndex({age: 1, tel: -1},{background: 'true'})
  2 {
  3         "numIndexesBefore" : 3,
  4         "numIndexesAfter" : 3,
  5         "note" : "all indexes already exist",
  6         "ok" : 1
  7 }
 

1.3 查看索引

  1 > db.age01.getIndexes()

1.4 查看集合索引大小

  1 > db.age01.totalIndexSize()

1.5 删除指定集合

  1 > db.age01.dropIndex('age_1_tel_-1')
  2 { "nIndexesWas" : 3, "ok" : 1 }
 

1.6 删除所有索引

  1 > db.age01.dropIndexes()
  2 {
  3         "nIndexesWas" : 2,
  4         "msg" : "non-_id indexes dropped for collection",
  5         "ok" : 1
  6 }
 

二 MongoDB聚合

2.1 aggregate() 方法

MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。
MongoDB中聚合的方法使用aggregate()。
语法格式:
  1 > db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
  2 [root@uhost ~]# mongo --host 172.24.9.225 --port 27017 -u useradmin -p useradmin
  3 > use mydb
  4 > db.age01.aggregate([{$group: {_id: "$tel", tel: {$sum: 1}}}])
  5 { "_id" : "123456784", "tel" : 1 }
  6 { "_id" : "188888888", "tel" : 2 }
  7 { "_id" : "155555555", "tel" : 1 }
 
提示:以上操作为统计所有各个tel的个数,类似select tel count(*) from age01 group by tel。

2.2 聚合表达式

表达式
描述
实例
$sum
计算总和。
db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg
计算平均值
db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min
获取集合中所有文档对应值得最小值。
db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max
获取集合中所有文档对应值得最大值。
db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$push
在结果文档中插入值到一个数组中。
db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSet
在结果文档中插入值到一个数组中,但不创建副本。
db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$first
根据资源文档的排序获取第一个文档数据。
db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$last
根据资源文档的排序获取最后一个文档数据
db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

三 管道

3.1 管道的概念

管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。
MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。
聚合框架常用操作:
  • $project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
  • $match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
  • $limit:用来限制MongoDB聚合管道返回的文档数。
  • $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
  • $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
  • $group:将集合中的文档分组,可用于统计结果。
  • $sort:将输入文档排序后输出。
  • $geoNear:输出接近某一地理位置的有序文档。
  1 [root@uhost ~]# mongo --host 172.24.9.225 --port 27017 -u useradmin -p useradmin
  2 > use mydb
  3 > db.age01.aggregate({$project: {name: 1, tel: 1,}}).pretty()
 
001
提示:_id默认为输出,可通过_id: 0关闭_id的输出。
  1 > db.age01.aggregate([{$match : {age: {$gt: '10', $lt: '20'}}},{$group: {_id: null, count: {$sum: 1}}}])
  2 { "_id" : null, "count" : 2 }			#$match过滤出符合条件的数据,然后$group进行再次处理。
 

3.2 时间聚合

  1 db.getCollection('m_msg_tb').aggregate(
  2 [
  3     {$match:{m_id:10001,mark_time:{$gt:new Date(2017,8,0)}}},
  4     {$group: {
  5        _id: {$dayOfMonth:'$mark_time'},
  6         pv: {$sum: 1}
  7         }
  8     },
  9     {$sort: {"_id": 1}}
 10 ])
 
时间关键字如下:
  • $dayOfYear: 返回该日期是这一年的第几天(全年 366 天)。
  • $dayOfMonth: 返回该日期是这一个月的第几天(1到31)。
  • $dayOfWeek: 返回的是这个周的星期几(1:星期日,7:星期六)。
  • $year: 返回该日期的年份部分。
  • $month: 返回该日期的月份部分( 1 到 12)。
  • $week: 返回该日期是所在年的第几个星期( 0 到 53)。
  • $hour: 返回该日期的小时部分。
  • $minute: 返回该日期的分钟部分。
  • $second: 返回该日期的秒部分(以0到59之间的数字形式返回日期的第二部分,但可以是60来计算闰秒)。
  • $millisecond:返回该日期的毫秒部分( 0 到 999)。
  • $dateToString: { $dateToString: { format: , date: } }。

Guess you like

Origin www.cnblogs.com/itzgr/p/10980919.html